Member Avatar for Rahul47

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

#include<stdio.h>

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]);
    }
    fclose(p);
    getch();
    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.

396d203f4ccf7f63b643727709ef4bae

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.

Member Avatar for Rahul47

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'
etc.

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]);
    }
Member Avatar for Rahul47

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)

Member Avatar for Rahul47

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.

Member Avatar for Rahul47

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.