C programming question?

2009-05-26 10:05 am
int main(){
char* abc = "abcdefgh";

printf("%s", *(abc + 1));

return 0;
}

-----------------
I get a segmentation fault for this code in C, can someone tell me what's wrong, and how can I fix this =) Thank you.

回答 (3)

2009-05-26 11:54 am
✔ 最佳答案
The problem is *(abc+1) is a character not a string
This will work
printf("%s",abc + 1); // if u want the string from 2nd character to print
or
printf("%c",*(abc+1)); // if u want to print the 2nd character
according to what u want, u use one of the above
2009-05-26 10:20 am
*(abc + 1)

That means a pointer to (your pointer plus 1)
pointer(pointer + 1)

Lets say that your pointer -
char* abc = "abcdefgh"

Let is say that your 'a' is in address 1000, but our 'abc' is at location 100.

Which means that abc = 1000 (equals the address it points to)
Or that address locatio 100 holds the value 1000

Then *() is a pointer to what ever is in the brackets.

So we have 'pointer to'( abc + 1)
Which means 'pointer to'( 100 + 1 )

So print("%s",,whatever address 101 points to)
Which is effectively a random address. Sometimes you may get a segment fault, other times it may accidentally point to something printable that just happens to have a string terminator.
2009-05-26 10:15 am
how can u add number and character(abcedef+1)
Try again.


收錄日期: 2021-05-01 12:24:32
原文連結 [永久失效]:
https://hk.answers.yahoo.com/question/index?qid=20090526020531AAExtLy

檢視 Wayback Machine 備份