Search Results

Search found 1848 results on 74 pages for 'printf'.

Page 26/74 | < Previous Page | 22 23 24 25 26 27 28 29 30 31 32 33  | Next Page >

  • Waiting for data via select not working

    - by BSchlinker
    I'm currently working on a project which involves multiple clients connected to a server and waiting for data. I'm using select and monitoring the connection for incoming data. However, the client just continues to print nothing, acting as if select has discovered incoming data. Perhaps I'm attacking this wrong? For the first piece of data the server does send, it is displayed correctly. However, the server then disconnects and the client continues to spew blank lines. FD_ZERO(&readnet); FD_SET(sockfd, &readnet); while(1){ rv = select(socketdescrip, &readnet, NULL, NULL, &timeout); if (rv == -1) { perror("select"); // error occurred in select() } else if (rv == 0) { printf("Connection timeout! No data after 10 seconds.\n"); } else { // one or both of the descriptors have data if (FD_ISSET(sockfd, &readnet)) { numbytes = recv(sockfd, buf, sizeof buf, 0); printf("Data Received\n"); buf[numbytes] = '\0'; printf("client: received '%s'\n",buf); sleep(10); } } }

    Read the article

  • std::map keys in C++

    - by Soumava
    I have a requirement to create two different maps in C++. The Key is of type CHAR * and the Value is a pointer to a struct. I am filling 2 maps with these pairs, in separate iterations. After creating both maps I need find all such instances in which the value of the string referenced by the CHAR * are same. For this i am using the following code : typedef struct _STRUCTTYPE { .. } STRUCTTYPE, *PSTRUCTTYPE; typedef pair {CHAR *,PSTRUCTTYPE} kvpair; .. CHAR *xyz; PSTRUCTTYPE abc; after filling the information; Map.insert (kvpair(xyz,abc)); the above is repeated x times for the first map, and y times for the second map. after both are filled out; std::map {CHAR *, PSTRUCTTYPE} :: iterator Iter,findIter; for (Iter=iteratedMap-begin();Iter!=iteratedMap-end();mapIterator++) { char *key = Iter-first; printf("%s\n",key); findIter=otherMap-find(key); //printf("%u",findIter-second); if (findIter!=otherMap-end()) { printf("Match!\n"); } } The above code does not show any match, although the list of keys in both maps show obvious matches. My understanding is that the equals operator for CHAR * just equates the memory address of the pointers. My question is, what should i do to alter the equals operator for this type of key or could I use a different datatype for the string? *note : {} has been used instead of angle brackets as the content inside angle brackets was not showing up in the post.

    Read the article

  • Decimal To Octal Converter, last digit issue

    - by Srishan Supertramp
    I tried making a C program to convert a user entered decimal number to octal. I wrote the C code with my own logic without any research of how other users try to do it. It works fine for the number 601 and some other numbers but for most numbers it returns the octal equivalent with the last digit being 1 less than it should be. For 75 it returns 112 instead of 113. I realize using printf with %o gets the job done but it's kind of defeating the purpose of learning to program. Here's my code: #include <stdio.h> #include <math.h> /* converting decimal to octal */ int main() { int n,x,y,p,s; printf("Enter a decimal number "); scanf("%d",&x); s=0;p=0; while (x!=0) { y=x%8; s=s+y*pow(10,p); x=(x-y)/8; p=p+1; } printf("the octal equivalent is: %d\n",s); getch(); return 0; }

    Read the article

  • Are vector assignments copied by value or by reference in Google's Go language?

    - by Brian T Hannan
    In the following code, I create one peg puzzle then do a move on it which adds a move to its movesAlreadyDone vector. Then I create another peg puzzle then do a move on it which adds a move to its movesAlreadyDone vector. When I print out the values in that vector for the second one, it has the move in it from the first one along with the move from the second one. Can anyone tell me why it seems to be assigning by reference and not value? Are vector assignments copied by value or by reference in Google's Go language? package main import "fmt" import "container/vector" type Move struct { x0, y0, x1, y1 int } type PegPuzzle struct { movesAlreadyDone * vector.Vector; } func (p *PegPuzzle) InitPegPuzzle(){ p.movesAlreadyDone = vector.New(0); } func NewChildPegPuzzle(parent *PegPuzzle) *PegPuzzle{ retVal := new(PegPuzzle); retVal.movesAlreadyDone = parent.movesAlreadyDone; return retVal } func (p *PegPuzzle) doMove(move Move){ p.movesAlreadyDone.Push(move); } func (p *PegPuzzle) printPuzzleInfo(){ fmt.Printf("-----------START----------------------\n"); fmt.Printf("moves already done: %v\n", p.movesAlreadyDone); fmt.Printf("------------END-----------------------\n"); } func main() { p := new(PegPuzzle); cp1 := new(PegPuzzle); cp2 := new(PegPuzzle); p.InitPegPuzzle(); cp1 = NewChildPegPuzzle(p); cp1.doMove(Move{1,1,2,3}); cp1.printPuzzleInfo(); cp2 = NewChildPegPuzzle(p); cp2.doMove(Move{3,2,5,1}); cp2.printPuzzleInfo(); } Any help will be greatly appreciated. Thanks!

    Read the article

  • I can't compile this code

    - by heshim
    #include <stdio.h> #define IN 1 /* inside a word */ #define OUT 0 /* outside a word */ /* count lines, words, and characters in input */ main() { int c, nl, nw, nc, state; state = OUT; nl = nw = nc = 0; while ((c = getchar()) != EOF) { ++nc; if (c == '\n') ++nl; if (c == ' ' || c == '\n' || c = '\t') state = OUT; else if (state == OUT) { state = IN; ++nw; } } printf("%d %d %d\n", nl, nw, nc); } I got K&R book but there are some codes that don't compile ! it gives me - 19 C:\Users\Nom\Desktop\Untitled1.c invalid lvalue in assignment edit: now it works, thanks guys, but now it does nothing ! the printf statement doesn't work. It opens the dos console, I type anything and it just return a new line. I'm using Dev-C++ 4.9.9.2 I put the printf statement inside the while loop and it works now. thanks

    Read the article

  • throwing exception from APCProc crashes program

    - by lazy_banana
    I started to do some research on how terminate a multithreaded application properly and I found those 2 post(first, second) about how to use QueueUserAPC to signal other threads to terminate. I thought I should give it a try, and the application keeps crashing when I throw the exception from the APCProc. Code: #include <stdio.h> #include <windows.h> class ExitException { public: char *desc; DWORD exit_code; ExitException(char *desc,int exit_code): desc(desc), exit_code(exit_code) {} }; //I use this class to check if objects are deconstructed upon termination class Test { public: char *s; Test(char *s): s(s) { printf("%s ctor\n",s); } ~Test() { printf("%s dctor\n",s); } }; DWORD CALLBACK ThreadProc(void *useless) { try { Test t("thread_test"); SleepEx(INFINITE,true); return 0; } catch (ExitException &e) { printf("Thread exits\n%s %lu",e.desc,e.exit_code); return e.exit_code; } } void CALLBACK exit_apc_proc(ULONG_PTR param) { puts("In APCProc"); ExitException e("Application exit signal!",1); throw e; return; } int main() { HANDLE thread=CreateThread(NULL,0,ThreadProc,NULL,0,NULL); Sleep(1000); QueueUserAPC(exit_apc_proc,thread,0); WaitForSingleObject(thread,INFINITE); puts("main: bye"); return 0; } My question is why does this happen? I use mingw for compilation and my OS is 64bit. Can this be the reason?I read that you shouldn't call QueueApcProc from a 32bit app for a thread which runs in a 64bit process or vice versa, but this shouldn't be the case.

    Read the article

  • Getting the full-name of the current user, returns an empty string (C#/C++)

    - by Nir
    I try to get the full-name of the current log-in user (Fullname, not username). The following code C#, C++ works fine but on XP computers not connected to the Net, I get empty string as result if I run it ~20 minutes after login (It runs OK whithin the first ~20 minutes after login) A Win32 API (GetUserNameEx) is used rather that PrincipalContext since it PrincipalContext may takes up to 15 seconds when working offline. Any Help why am I getting an empty string as result though a user full name is specified??? - C# Code public static string CurrentUserFullName { get { const int EXTENDED_NAME_FORMAT_NAME_DISPLAY = 3; StringBuilder userName = new StringBuilder(256); uint length = (uint) userName.Capacity; string ret; if (GetUserNameEx(EXTENDED_NAME_FORMAT_NAME_DISPLAY, userName, ref length)) { ret = userName.ToString(); } else { int errorCode = Marshal.GetLastWin32Error(); throw new Win32Exception("GetUserNameEx Failed. Error code - " + errorCode); } return ret; } } [DllImport("Secur32.dll", CharSet = CharSet.Auto, SetLastError = true)] private static extern bool GetUserNameEx(int nameFormat, StringBuilder lpNameBuffer, ref uint lpnSize); - Code in C++ #include "stdafx.h" #include <windows.h> #define SECURITY_WIN32 #include <Security.h> #pragma comment( lib, "Secur32.lib" ) int _tmain(int argc, _TCHAR* argv[]) { char szName[100]; ULONG nChars = sizeof( szName ); if ( GetUserNameEx( NameDisplay, szName, &nChars ) ) { printf( "Name: %s\n", szName); } else { printf( "Failed to GetUserNameEx\n" ); printf( "%d\n", GetLastError() ); } return 0; }

    Read the article

  • replacing elements horizontally and vertically in a 2D array

    - by wello horld
    the code below ask for the user's input for the 2D array size and prints out something like this: (say an 18x6 grid) .................. .................. .................. .................. .................. .................. code starts here: #include <stdio.h> #define MAX 10 int main() { char grid[MAX][MAX]; int i,j,row,col; printf("Please enter your grid size: "); scanf("%d %d", &row, &col); for (i = 0; i < row; i++) { for (j = 0; j < col; j++) { grid[i][j] = '.'; printf("%c ", grid[i][j]); } printf("\n"); } return 0; } I now ask the user for a string, then ask them where to put it for example: Please enter grid size: 18 6 Please enter word: Hello Please enter location: 0 0 Output: Hello............. .................. .................. .................. .................. .................. Please enter location: 3 4 Output: .................. .................. .................. ..Hello........... .................. .................. program just keeps going. Any thoughts on how to modify the code for this? PS: Vertical seems way hard, but I want to start on horizontal first to have something to work on.

    Read the article

  • basic file input using C

    - by user1781966
    So im working on learning how to do file I/O, but the book I'm using is terrible at teaching how to receive input from a file. Below is is their example of how to receive input from a file, but it doesn't work. I have copied it word for word, and it should loop through a list of names until it reaches the end of the file( or so they say in the book), but it doesn't. In fact if I leave the while loop in there, it doesn't print anything. #include <stdio.h> #include <conio.h> int main() { char name[10]; FILE*pRead; pRead=fopen("test.txt", "r"); if (pRead==NULL) { printf("file cannot be opened"); }else printf("contents of test.txt"); fscanf(pRead,"%s",name); while(!feof(pRead)) { printf("%s\n",name); fscanf(pRead, "%s", name); } getch(); } Even online, every beginners tutorial I see does some variation of this, but I can't seem to get it to work even a little bit.

    Read the article

  • Uniq in awk; removing duplicate values in a column using awk

    - by D W
    I have a large datafile in the following format below: ENST00000371026 WDR78,WDR78,WDR78, WD repeat domain 78 isoform 1,WD repeat domain 78 isoform 1,WD repeat domain 78 isoform 2, ENST00000371023 WDR32 WD repeat domain 32 isoform 2 ENST00000400908 RERE,KIAA0458, atrophin-1 like protein isoform a,Homo sapiens mRNA for KIAA0458 protein, partial cds., The columns are tab separated. Multiple values within columns are comma separated. I would like to remove the duplicate values in the second column to result in something like this: ENST00000371026 WDR78 WD repeat domain 78 isoform 1,WD repeat domain 78 isoform 1,WD repeat domain 78 isoform 2, ENST00000371023 WDR32 WD repeat domain 32 isoform 2 ENST00000400908 RERE,KIAA0458 atrophin-1 like protein isoform a,Homo sapiens mRNA for KIAA0458 protein, partial cds., I tried the following code below but it doesn't seem to remove the duplicate values. awk ' BEGIN { FS="\t" } ; { split($2, valueArray,","); j=0; for (i in valueArray) { if (!( valueArray[i] in duplicateArray)) { duplicateArray[j] = valueArray[i]; j++; } }; printf $1 "\t"; for (j in duplicateArray) { if (duplicateArray[j]) { printf duplicateArray[j] ","; } } printf "\t"; print $3 }' knownGeneFromUCSC.txt How can I remove the duplicates in column 2 correctly?

    Read the article

  • Data conversion from accelerometer

    - by mrigendra
    Hi all I am working on an accelerometer bma220 , and its datasheet says that data is in 2's complement form.So what i had to do was getting that 8 bit data in any 8 bit signed char and done. the bma220 have an 8 bit register of which first 6 bits are data and last two are zero. void properdata(int16_t *msgData) { printf("\nin proper data\n"); int16_t temp, i; for(i=0; i<3; i++) { temp = *(msgData + i); printf("temp = %d sense = %d\n", temp, sense); temp = temp >> 2; // only 6 bits data temp = temp / sense; //decimal value * .0625 = value in g printf("temp = %d\n", temp); } } in this program i am taking data in a unsigned variable msgdata and doing all the calculations on a signed variable. I just need to know if this is the correct way to convert data?

    Read the article

  • uint64_t has incorrectly reached 18,446,744,071,590,568,320

    - by user3400450
    Whenever I input an age of 65 or less, I get a number somewhere less than 2,100,000. However, when I input an age of 68 or higher, the result is instantly put at 18,446,744,071,590,568,320, which is the maximum value for uint64_t. I have no idea why there is this jump in results. It works fine all the way until about 2,100,000. // How many seconds have I lived? #include <stdio.h> #include <string> #include <cstdint> using namespace std; string addCommas(uint64_t answer); int main () { int seconds = 60, minutes = 60, hours = 24, days = 365; int years; uint64_t secondsLived, secondsAwake; printf("How many years have you lived? "); scanf("%d",&years); secondsLived = seconds*minutes*hours*days*years; secondsAwake = (float)secondsLived*0.666; printf("\nYou have existed for %s seconds\n",addCommas(secondsLived).c_str()); printf("You have been awake for %s seconds\n",addCommas(secondsAwake).c_str()); } string addCommas(uint64_t answer){ string num = to_string(answer); int insertplace = (int)num.length() - 3; while (insertplace > 0) { num.insert(insertplace, ","); insertplace-=3; } return num; } Here are a couple outputs: How many years have you lived? 67 You have existed for 2,112,912,000 seconds You have been awake for 1,407,199,392 seconds How many years have you lived? 69 You have existed for 18,446,744,071,590,568,320 seconds You have been awake for 12,285,531,553,090,562,048 seconds

    Read the article

  • Passing array of pointers to another class

    - by user310153
    Hi, I am trying to do the following: in main.cpp: // Create an array of pointers to Block objects Block *blk[64]; for (i=0; i<8; i++) { for (j=0; j<8; j++) { int x_low = i*80; int y_low = j*45; blk[j*8+i] = new Block(30, x_low+40.0f, y_low+7.5f, &b); } } And then I am trying to pass it to the graphics object I have created: Graphics g(640, 480, &b, &p, blk[0], number_of_blocks); the graphics constructor looks like: Graphics::Graphics(int width, int height, Ball *b, Paddle *p, Block *blk, int number_of_blocks) { if I look at what is contained in the array from the graphics object, only the first item exists and then all the other items are in hyperspace: for (int i=0; i<64; i++) { printf("for block %d, %f, %f ", i, (_blk+(sizeof(_blk)*i))->_x_low, (_blk+(sizeof(_blk)*i))->_y_low); printf("blah %d\n", (_blk+(sizeof(_blk)*i))); } and if I look at the addresses, they are different (6956552 rather than 2280520 when I examine the addresses in the main class using: printf(" blah %d\n", &blk[j*8*i]); I am sure there must be something subtle I am doing wrong as its like I have copied the first item from the blk array to a new address when passed to the graphics object. Does this make sense? Any ideas? Cheers, Scott

    Read the article

  • why doesnt this program print?

    - by Alex
    What I'm trying to do is to print my two-dimensional array but i'm lost. The first function is running perfect, the problem is the second or maybe the way I'm passing it to the "Print" function. #include <stdio.h> #include <stdlib.h> #define ROW 2 #define COL 2 //Memory allocation and values input void func(int **arr) { int i, j; arr = (int**)calloc(ROW,sizeof(int*)); for(i=0; i < ROW; i++) arr[i] = (int*)calloc(COL,sizeof(int)); printf("Input: \n"); for(i=0; i<ROW; i++) for(j=0; j<COL; j++) scanf_s("%d", &arr[i][j]); } //This is where the problem begins or maybe it's in the main void print(int **arr) { int i, j; for(i=0; i<ROW; i++) { for(j=0; j<COL; j++) printf("%5d", arr[i][j]); printf("\n"); } } void main() { int *arr; func(&arr); print(&arr); //maybe I'm not passing the arr right ? }

    Read the article

  • Fastest container or algorithm for unique reusable ids in C++

    - by gman
    I have a need for unique reusable ids. The user can choose his own ids or he can ask for a free one. The API is basically class IdManager { public: int AllocateId(); // Allocates an id void FreeId(int id); // Frees an id so it can be used again bool MarkAsUsed(int id); // Let's the user register an id. // returns false if the id was already used. }; Assume ids happen to start at 1 and progress, 2, 3, etc. This is not a requirement, just to help illustrate. IdManager mgr; mgr.MarkAsUsed(3); printf ("%d\n", mgr.AllocateId()); printf ("%d\n", mgr.AllocateId()); printf ("%d\n", mgr.AllocateId()); Would print 1 2 4 Because id 3 has already been declared used. What's the best container / algorithm to both remember which ids are used AND find a free id? If you want to know the a specific use case, OpenGL's glGenTextures, glBindTexture and glDeleteTextures are equivalent to AllocateId, MarkAsUsed and FreeId

    Read the article

  • parsing ssid with iwconfig in c

    - by user1781595
    I am about building a bar for DWM (ubuntu linux), showing wifi details such as the ssid. Thats my code: #include <stdio.h> #include <stdlib.h> int main( int argc, char *argv[] ) { FILE *fp; int status; char path[1035]; /* Open the command for reading. */ fp = popen("iwconfig", "r"); if (fp == NULL) { printf("Failed to run command\n" ); exit; } char s[500]; /* Read the output a line at a time - output it. */ while (fgets(path, sizeof(path)-1, fp) != NULL) { sprintf(s,"%s%s",s, path); } //printf("%s",s); /* close */ pclose(fp); char delimiter[1] = "s"; char *ptr; ptr = strtok(s, delimiter); printf("SSID: %s\n", ptr); return 0; } i am getting overflowerrors and dont know what to do. I dont think, thats a good way to get the ssid either... :/ Suggestions?

    Read the article

  • Works for Short Input, Fails for Long Input. How to Solve?

    - by r0ach
    I've this program which finds substring in a string. It works for small inputs. But fails for long inputs. Here's the program: //Find Substring in given String #include <stdio.h> #include <string.h> main() { //Variable Initialization int i=0,j=0,k=0; char sentence[50],temp[50],search[50]; //Gets Strings printf("Enter Sentence: "); fgets(sentence,50,stdin); printf("Enter Search: "); fgets(search,50,stdin); //Actual Work Loop while(sentence[i]!='\0') { k=i;j=0; while(sentence[k]==search[j]) { temp[j]=sentence[k]; j++; k++; } if(strcmp(temp,search)==0) break; i++; } //Output Printing printf("Found string at: %d \n",k-strlen(search)); } Works for: Enter Sentence: good evening Enter Search: evening Found string at 6 Fails for: Enter Sentence: dear god please make this work Enter Search: make Found string at 25 Which is totally wrong. Can any expert find me a solution? P.S: This is kinda like reinventing the wheel since strstr() has this functionality. But I'm trying for a non-library way of doing it.

    Read the article

  • Outer product using CBLAS

    - by The Dude
    I am having trouble utilizing CBLAS to perform an Outer Product. My code is as follows: //===SET UP===// double x1[] = {1,2,3,4}; double x2[] = {1,2,3}; int dx1 = 4; int dx2 = 3; double X[dx1 * dx2]; for (int i = 0; i < (dx1*dx2); i++) {X[i] = 0.0;} //===DO THE OUTER PRODUCT===// cblas_dgemm(CblasRowMajor, CblasNoTrans, CblasTrans, dx1, dx2, 1, 1.0, x1, dx1, x2, 1, 0.0, X, dx1); //===PRINT THE RESULTS===// printf("\nMatrix X (%d x %d) = x1 (*) x2 is:\n", dx1, dx2); for (i=0; i<4; i++) { for (j=0; j<3; j++) { printf ("%lf ", X[j+i*3]); } printf ("\n"); } I get: Matrix X (4 x 3) = x1 (*) x2 is: 1.000000 2.000000 3.000000 0.000000 -1.000000 -2.000000 -3.000000 0.000000 7.000000 14.000000 21.000000 0.000000 But the correct answer is found here: https://www.sharcnet.ca/help/index.php/BLAS_and_CBLAS_Usage_and_Examples I have seen: Efficient computation of kronecker products in C But, it doesn't help me because they don't actually say how to utilize dgemm to actually do this... Any help? What am I doing wrong here?

    Read the article

  • Array loading with doubles in C

    - by user2892120
    I am trying to load a 3x8 array of doubles but my code keeps outputting 0.00 for all of the values. The code should be outputting the array (same as the input) under the Read#1 Read#2 Read#3 lines, with the average under average. Here is my code: #include <stdio.h> double getAvg(double num1, double num2, double num3); int main() { int numJ,month,day,year,i,j; double arr[3][8]; scanf("%d %d %d %d",&numJ,&month,&day,&year); for (i = 0; i < 8; i++) { scanf("%f %f %f",&arr[i][0], &arr[i][1], &arr[i][2]); } printf("\nJob %d Date: %d/%d/%d",numJ,month,day,year); printf("\n\nLocation Read#1 Read#2 Read#3 Average"); for (j = 0; j < 8; j++) { printf("\n %d %.2f %.2f %.2f %.2f",j+1,arr[j][0],arr[j] [1],arr[j][2],getAvg(arr[j][0],arr[j][1],arr[j][2])); } return 0; } double getAvg(double num1, double num2, double num3) { double avg = (num1 + num2 + num3) / 3; return avg; } Input example: 157932 09 01 2013 0.00 0.00 0.00 0.36 0.27 0.23 0.18 0.16 0.26 0.27 0.00 0.34 0.24 0.00 0.31 0.16 0.33 0.36 0.29 0.36 0.00 0.21 0.36 0.00

    Read the article

  • When are temporaries created as part of a function call destroyed?

    - by Michael Mrozek
    Is a temporary created as part of an argument to a function call guaranteed to stay around until the called function ends, even if the temporary isn't passed directly to the function? There's virtually no chance that was coherent, so here's an example: class A { public: A(int x) : x(x) {printf("Constructed A(%d)\n", x);} ~A() {printf("Destroyed A\n");} int x; int* y() {return &x;} }; void foo(int* bar) { printf("foo(): %d\n", *bar); } int main(int argc, char** argv) { foo(A(4).y()); } If A(4) were passed directly to foo it would definitely not be destroyed until after the foo call ended, but instead I'm calling a method on the temporary and losing any reference to it. I would instinctively think the temporary A would be destroyed before foo even starts, but testing with GCC 4.3.4 shows it isn't; the output is: Constructed A(4) foo(): 4 Destroyed A The question is, is GCC's behavior guaranteed by the spec? Or is a compiler allowed to destroy the temporary A before the call to foo, invaliding the pointer to its member I'm using?

    Read the article

  • Declaring arrays in c language without initial size

    - by user2534857
    this is the question-- Write a program to manipulate the temperature details as given below. - Input the number of days to be calculated. – Main function - Input temperature in Celsius – input function - Convert the temperature from Celsius to Fahrenheit.- Separate function - find the average temperature in Fahrenheit. how can I make this program without initial size of array ?? #include<stdio.h> #include<conio.h> void input(int); int temp[10]; int d; void main() { int x=0; float avg=0,t=0; printf("\nHow many days : "); scanf("%d",&d); input(d); conv(); for(x=0;x<d;x++) { t=t+temp[x]; } avg=t/d; printf("Avarage is %f",avg); getch(); } void input(int d) { int x=0; for(x=0;x<d;x++) { printf("Input temperature in Celsius for #%d day",x+1); scanf("%d",&temp[x]); } } void conv() { int x=0; for(x=0;x<d;x++) { temp[x]=1.8*temp[x]+32; } }

    Read the article

  • Second user-defined function returns garbage value?

    - by mintyfresh
    I have been teaching myself C programming, and I've come to a difficult point with using variables across functions. When, I compile this program and run it, the function askBirthYear returns the correct value, but sayAgeInYears returns either 0 or a garbage value. I believe it has something to do with how I used the variable birthYear, but I'm stumped on how to fix the issue. Here is the code: #include <stdio.h> #include <stdlib.h> int askBirthYear(int); void sayAgeInYears(int); int birthYear; int main(void) { askBirthYear(birthYear); sayAgeInYears(birthYear); return EXIT_SUCCESS; } void askBirthYear(int birthYear) { printf("Hello! In what year were you born?\n"); scanf("%d", &birthYear); printf("Your birth year is %d.\n", birthYear); return birthYear; } void sayAgeInYears(int birthYear) { int age; age = 2012 - birthYear; printf("You are %d years old.\n", age); }

    Read the article

  • Cannot determine why pointer variable will not address elements in a string in this program?

    - by Smith Will Suffice
    I am attempting to utilize a pointer variable to access elements of a string and there are issues with my code generating a compilation error: #include <stdio.h> #define MAX 29 char arrayI[250]; char *ptr; int main(void) { ptr = arrayI; puts("Enter string to arrayI: up to 29 chars:\n"); fgets(arrayI, MAX, stdin); printf("\n Now printing array by pointer:\n"); printf("%s", *ptr); ptr = arrayI[1]; //(I set the pointer to the second array char element) printf("%c", *ptr); //Here is where I was wanting to use my pointer to //point to individual array elements. return 0; } My compiler crieth: [Warning] assignment makes pointer from integer without a cast [enabled by default] I do not see where my pointer was ever assigned to the integer data type? Could someone please explain why my attempt to implement a pointer variable is failing? Thanks all!

    Read the article

  • Struct arrays in C

    - by ThomasTheTankEngine
    Hi I'm having trouble trying to initializing each element of the struct array. When I try and assign the value ZERO to both 'bSize' and 'msgs', it doesn't work as it errors out when i get to malloc. In the printf statement it prints a -1852803823 number. Excuse the messy code as i'm playing around trying to figure it out. struct message{ int *data; int bSize; int msgs; }; int main(int argc, char *argv[]) { ..... } void getSchedFile (FILE *file, int **schd) { struct message sMsg[nodeCount]; const int pakSize = 6; // Iniitialise message buffer for (int i=0; i<nodeCount; i++){ sMsg[i].bSize = 0; sMsg[i].msgs = 0; printf("bSize %d\n",sMsg[i].bSize); } /* Get the number of bytes */ fseek(file, 0L, SEEK_SET); int time; while((fscanf(file, "%d", &time)) != EOF){ int src; fscanf(file, "%d", &src); // get source node id // These are here for easier reading code int aPos = sMsg[src].bSize; int nMsg = sMsg[src].msgs; printf("size %d\n", sMsg[src].bSize); if (sMsg[src].bSize==0){ sMsg[src].data = malloc( pakSize * sizeof(int)); }else{ sMsg[src].data = realloc(sMsg[src].data, (aPos+pakSize)*sizeof(int)); }

    Read the article

  • Reading a text file, and performing actions based on strings read

    - by user1691766
    Let me start off by saying that I really am quite new to C. So basically I have a text file (contains around 30 assembly instructions, separated by new lines), and I am successfully reading them into my program. From here I need to perform certain actions based off each instruction. I would assume the best way to do this would be via a switch-case statement. However I am encountering a lot of problems due to me trying to compare strings that are 33 characters long. Can anyone please offer me advice on what I am doing wrong, or offer an alternative? Thanks in advance. Here is what I have so far: char instruction[29][ 33 ]; int i,run; i = 0; run = 1; FILE *instPtr; /* LOADING INSTRUCTIONS FROM FILE INTO "instruction" ARRAY*/ if ( ( instPtr = fopen("MIPSinstructions.txt", "r") ) == NULL ) { printf("File could not be opened\n"); } // end if else { fscanf( instPtr, "%s", instruction[0]); printf("%s\n", instruction[0]); while (!feof( instPtr ) ){ i++; fscanf( instPtr, "%s", instruction[i]); printf("%s\n", instruction[i]); } fclose( instPtr ); i = 0; // Reset the counter } //end else return 0; }

    Read the article

< Previous Page | 22 23 24 25 26 27 28 29 30 31 32 33  | Next Page >