The key thing to understand for both of your examples is that a char *
value stores the address of a byte in memory. By convention, C strings are represented as a pointer to the first byte of the string, with a null byte marking the end. When you assigned constant strings into your array, the compiler allocated the necessary memory and placed the pointers into your array, but when you are not using constants it is your responsibility to allocate the buffer to store the string, and then store that pointer in the array yourself.
In your second example you have allocated storage for several pointers to char
, but you have not made those pointers refer to valid buffers, so accessing them with either return garbage or crash the program. There are (at least) two ways to address this: either allocate a fixed-size buffer on the stack and store your data there, or dynamically allocate memory from the heap using malloc
.
The former has the advantage of handling the deallocation of the buffers automatically, but requires you to decide at compile time how much memory to allocate for each string:
char* dic[tam];
char buf[tam * 32]; // allocate 32 bytes per element.
for (int i = 0; i < tam; i++) {
// Make the pointers in ``dic`` refer to 32-byte offsets into the buffer.
dic[tam] = &(buf[tam * 32]);
}
You can also allocate dynamically using malloc
. You could actually allocate one big tam * 32
buffer this way too, but for the sake of example here's how to allocate a separate buffer for each element:
char* dic[tam];
for (int i = 0; i < tam; i++) {
// Allocate 32 bytes per element.
// (This value can be decided at runtime, if you want.)
dic[tam] = malloc(32);
}
But since this uses malloc
you need to be sure to clean up this memory before you return to avoid a memory leak. e.g. at the end of your routine:
for (int i = 0; i < tam; i++) {
// de-allocate the buffer we allocated earlier
free(dic[tam]);
}
(This method of calling malloc
multiple times in a loop may also cause memory fragmentation if you do it a lot, but that's an advanced topic not worth worrying about for a small program.)