Expert Novice
Expert Novice

Reputation: 1963

Issue with pointer to char

What seems to be the problem with this part of my code:

while(c != EOF){    
    c = fgetc(myFile);
    p[i++]=c;
    printf("%c", p[i]);
}

It does not seem to store the values in p[i] even though malloc succeeds, and prints garbage. However this code prints the characters fine:

while(c != EOF){    
    c = fgetc(myFile);
    //p[i++]=c;
    printf("%c", c);
}

p is a char* and i is initially 0. Asked in the question Not getting all characters after reading from file

What is the problem here?

Upvotes: 0

Views: 123

Answers (3)

crypted
crypted

Reputation: 10306

problem is,

while(c!=EOF){    
              c=fgetc(myFile);
              p[i++]=c;
              printf("%c",p[i]);
             }

look at the p[i++]=c, it stores the value of c in p[i] than increments i by one, so when you use p[i] to print the character you are referring to another memory location which possibly holds garbage.

Upvotes: 0

Hugh Brackett
Hugh Brackett

Reputation: 2706

You are incrementing i after you store the char, so you are printing the next position, which you haven't stored anything to yet.

change the lines to:

p[i]=c;
printf("%c",p[i++]); 

Upvotes: 0

cnicutar
cnicutar

Reputation: 182639

The line p[i++] = c stores the character and increments i. The next line prints p[i]but i has already been incremented. Try this:

while(c!=EOF){    
    c=fgetc(myFile);
    p[i]=c;
    printf("%c",p[i]);

    i++;
}

As a side note, you could probably rewrite it

while((c = fgetc(stdin)) != EOF)
    *p++ = c;

Upvotes: 3

Related Questions