I am a begginner at C so please bear with me;
I am aware that i can make an array statement as *c
or c[]
;
My question is about memset:
char str[] = "hello!";
memset (str,'-',2);
puts (str);
Works fine. But:
char *str = "hello!";
memset (str,'-',2);
puts (str);
Dont work,
I know that char *str = ...
is a normal array statement.
If anyone can help me with this one i Thank you!
The difference here is subtle - it's where the string is stored.
char str[] = "hello!";
allocates a string on the stack, which can be updated.
char *str = "hello!";
allocates a string in the programs const data segment and sets str to point to that segment. That segment can't be manipulated and your program crashes on memory access violation.
A modern computer has a complex memory layout, and a whole set of concepts you'll need to learn at some point, such as Virtual Memory and Paging and such as Stack and Heap.
A program being loaded into memory is segmented into different sections which are loaded to different pages with different permissions. The code and global const variables are loaded to pages which have no writing permissions (only read) - .text and .rodata segments respectively - while the stack and heap are allocated on pages which can be written to but can't be executed (.data and .bss).
The literal string "hello" in the 2nd example is allocated in the const segment (.rodata), and thus can't be altered. Moreover, if you define several strings like that
char *s1 = "Hello!";
char *s2 = "Hello!";
It's very likely that s1 == s2
will be true (address comparison!)
In the 1st example an actual array is being allocated on the stack and filled with the bytes containing "hello!\0"
(7 bytes). That memory CAN be manipulated since it is on the stack which is allocated on writable pages.