I'm still a newbie to C
char* str = (char*)malloc(512);
str = "hello";
*(str) = 'H'; // Segmentation fault
I get a Segmentation fault
on the third line trying to set an character
I know that str
is a pointer to the first char
and I can printf it
printf("%c\n", *str); // Output: h
Well, Is it in Read-Only memory? I'm not sure why that happened but I can change the whole pointer just like I did
str = "hello";
I can do that
char** str = (char**)malloc(512*sizeof(char*));
*str = "hello";
*(str+1) = "Yo!";
//*(str) = 'H';
printf("%s\n", *(str)); // Prints: hello
printf("%s\n", *(str+1)); // Prints: Yo!
from the last code, I can do this and still the same
str[0] = "hello";
str[1] = "Yo!";
The reason is that it's an array of pointers after all, I'm just changing that pointer like in the first code, with some index
and the reason why *(str+1) = "Yo!";
works, I'm incrementing the address or the 0 index of char*
which gives me the address of the next adjacent char*
from the last code, I cannot do things like
**(str) = 'H';
*(str)[0] = 'H';
str[0][0] = 'H';
except if I have an array of char
char str[5][10]; // allocated 5 strings slots, 10 max characters for each
*(str)[0] = 'H';
*(str[0]+1) = 'e';
str[0][2] = 'l';
str[0][3] = 'l';
*((*str)+4 )= 'o';
printf("%s\n", str[0]); // Prints: Hello
I can allocate 512
char and just use 12
, I can allocate 1024
char and still need more, I can go out of memory if I allocated too much
I've to use char* and I need to be able to change the value of an char
like I did in that last array
like, let's say I'm building an compiler, text editor...
I need to be able to allocate memory at runtime plus check some characters like ';'
Or an split()
function, which splits an char*
into an array of pointers
- Start copying
char[s]
intochar[n][i] // n = 0, ++i, ++s
- for each
';'
iteration inchar*
,i = 0, ++n
- return
char**
This can be done easily if I'm working with 2D arrays, but they're not, they're pointers...
How can we change the value of a char
in this pointer?
Why can we read any char
in this pointer and not write to it?
I don't have a full understanding of pointers yet, Sorry if something is wrong with the code, thanks.