I’m trying to write a response into a variable, and I can’t figure out how to do it.
This doesn’t work – screws up memory, but no protection errors:
for (int i = 0; i < 20; i++) {
list[i] = 'a';
}
Same with this – memory screwed up:
for (int i = 0; i < 20; i++) {
*(((int*)(list))+i) = 'a';
}
//I don't think this is a string issues as this doesn't help:
//*(((int*)(list))+20) = '\0';
This causes a bus error:
for (int i = 0; i < 20; i++) {
*list[i] = 'a';
}
This works as desired:
*list = "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa";
What am I doing wrong?
P.S. list is char**.
In C, a pointer can be used to represent an array, and a single string is an array of
char, or in other words, achar *. This means that achar **is an array of strings. So if you want to put characters into the first string (assuming that memory has already been allocated to it), you should uselist[0][i] = 'a';in the first loop – i.e., put'a'into positioniof the0th string.Another way of interpreting a
char **(which is the one I suspect is the one you’re supposed to use) is that it is a pointer that points to a pointer that points to an array ofchar. In that case, you can use the “outer” pointer to modify what the inner pointer points to; this can be used to first allocate the string and then write to it:In memory, this looks like this: