0

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 ?

4
Contributors
9
Replies
31
Views
3 Years
Discussion Span
Last Post by Rahul47
0

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.

Edited by Moschops

0

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

0

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.

0

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]);
    }

Edited by Moschops

0

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.

0

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.

0

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

This question has already been answered. Start a new discussion instead.
Be sure to adhere to our posting rules.