I learning these concepts, please help me why the following code is throwing a segmentation fault. My intention in this code is to print capital letter D and move to next address. Please explain me. thank u.
main()
{
char *ptr="C programming";
printf(" %c \n",++*ptr);
}
You are trying to modify a string literal, which is a non-modifiable object. That's why you get a segmentation fault.
Even if you simply call ptr[0]++, it will be a segmentation fault.
One solution is to change the declaration to:
char ptr[] = "C programming"
Then you can modify the char array.
They look similar? Yes, the string literal is still non-modifiable, but you have declared an array with its own space, which will be initialized by the string literal, and the array is stored in the stack, and thus modifiable.
Here is a full code example:
#include <stdio.h>
int test() {
char str[]="C programming";
char *ptr = str;
while(*ptr != '\0') {
// print original char,
printf("%c \n", *(ptr++));
// print original char plus 1, but don't change array,
// printf("%c \n", (*(ptr++))+1);
// modify char of array to plus 1 first, then print,
// printf("%c \n", ++(*(ptr++)));
}
return 0;
}
int main(int argc, char * argv[]) {
test();
return 0;
}
Tip: you should only enable one of the printf() lines at the same time, due to ++ operator.
Note that we declared a ptr and a str, because we can't use ++ operation on an array (you can't change the address of an array), thus ++str will get a compile error, while ++ptr won't.
(To answer your comment)
You might also want to know more about pointer or address or array or Linux process memory layout_ or data sections of a C program; try searching on Google, or refer to books like The C Programming Language, 2nd Edn and The Linux Programming Interface — though this is a question about C rather than Linux. There's also The Definitive C Book Guide and List on Stack Overflow.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With