Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

c - Find the fault or error

Can you find what is wrong with the following code?

int main(){
    char *p="hai friends",*p1;
    p1=p;
    while(*p!='') ++*p++;
    printf("%s %s",p,p1);
}

I expected it will print space followed by a string!

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The expression ++*p++; is equivalent to;

++*p; 
p++;

++*p; means

*p = *p + 1;

Because postfix ++ has higher precedence than the dereference operator *, it's applied on *p.

And p points to a constant string literal. In the above operation you are trying to "write on read only memory" — that is illegal — hence error.

Suggestions:

First — declare your an array that can be modified, you can't change string literals.
declare (read comments):

char string_array[] ="hai friends"; // notice `[]` in this declaration
                                    // that makes `string_array` array 

// to keep save original string do:
char p1[20]; // sufficient length  // notice here `p1` is not pointer.
strcpy(p1, string_array) ;

char *p = string_array;

Now you can modify pointer p and string_array[] array content.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...