Hi guys, here is my code that am working on this morning, and I came across a point when pointer operation went wrong.


int main(){
    char a[20]="Hello World !!!";
    char *ptr=a;
    FILE *p;
    p=fopen("new.txt", "w");
    int i;
    for (i=0; *ptr != '\0'; i++){
        fprintf(p,"%c", ptr[i]);
    return 0;

Initially I printed output on console, but then I was missing some lines. Thats why I decided to save it in a text file. Following is a snapshot of same as I was not able to upload .txt file here.


My question here is why after detecting a \0 character loop didn't terminated ?

Your for loop is always testing the same character; the first one. You are never changing the pointer, so ptr is always the pointing at the same place, so *ptr never changes.

You are never changing the pointer.

for (i=0; *ptr != '\0'; i++){
        fprintf(p,"%c", ptr[i]);

counter i is constantly incremented and so do pointer ptr

Moschops is correct.
When i = 0, ptr[i] will point to 'H' and *ptr will point to 'H'
When i = 1, ptr[i] will point to 'e' and *ptr will point to 'H'

counter i is constantly incremented and so do pointer

No, ptr[i] is changing, because i is changing. ptr stays the same the whole time.

I suspect you actually meant this:

for (i=0; *ptr[i] != '\0'; i++){
        fprintf(p,"%c", ptr[i]);

Well it is actually like this:

for (i=0; ptr[i] != '\0'; i++){
        fprintf(p,"%c", ptr[i]);

Thanx ddanbe for pointing that out and Moschops for corrections. That Solved my problem.

Note that ptr[i] can also be written as *(ptr + i)

Yep, thats why I used ptr[i] instead of *(ptr + i).

Just a quick word of advice. It is more efficient to use fwrite() or fputc() instead of fprintf() for writing characters to a file one at a time. This is because fprintf() needs to parse the format string whereas fwrite() and fputc() does not.

This only matters if you plan on dealing with very large files.

Thanx for that valuable advice N1GHTS, I will keep that in mind.
I really appreciate it.