Here is my code:
printf("%s\n", "test1");
char c = '2';
char * lines[2];
char * tmp1 = lines[0];
*tmp1 = c;
printf("%s\n", "test2");
I don’t see the second printf in console.
Question: Can anybody explain me what’s wrong with my code?
NOTE: I’m trying to learn C 🙂
This line:
declares an array of two
charpointers. However, you don’t actually initialize the pointers to anything. So later when you do*tmp1 = (char)c;then you assign the charactercto somewhere in memory, possibly even address zero (i.e.NULL) which is a bad thing.The solution is to either create the array as an array of arrays, like
This declares lines to have two arrays of 30 characters each, and since strings needs a special terminator character you can have string of up to 29 characters in them.
The second solution is to dynamically allocate memory for the strings:
Essentially this does the same as the above array-of-arrays declaration, but allocates the memory on the heap.
Of course, maybe you just wanted a single string of a single character (plus the terminator), then you were almost right, just remove the asterisk: