A newbie question:
I was practice assignment to a char pointer, but found there was nothing printed out. Here is the code:
#include <stdio.h>
int main (void)
{
char * option_string = NULL;
option_string = (char*)malloc(sizeof(5));
memset(option_string, 0, sizeof(char) * 5);
int j;
for ( j = 0; j < 5; j++)
{
*option_string++ = 'a';
}
printf("print options_string: %s\n", option_string); //!nothing was printed out!
free(option_string);
return 0;
}
Thanks in advance!
Your problem is that within the loop, you write
*option_string++. This means that once the loop is done, you’re going to be pointing past the end of the string:Note that this reveals a second problem with your code: strings in C are null-terminated, but this string will eventually contain “aaaaa” and then… who knows? Garbage, most likely, but you can’t tell. You need a six-length string. Fixing the first problem means using simple indexing instead:
option_string[j] = 'a'. If you really want the*option_string++method, you’ll have to save and restoreoption_string(char * real_option_string = option_string; ... option_string = real_option_string;), but I wouldn’t recommend it. Fixing both of these bugs, and a couple of style things, gives you:The other thing I changed was your
mallocusage. I feel likecallocis a better stylistic choice here;calloc(count, size)allocatescountobjects of sizesize, and zeros them. It’s likemalloc(count*size)plus a memset, but feels cleaner to me. You also shouldn’t have a cast onmalloc/calloc/etc., generally speaking (it can obscure useful warnings), and you need to allocate six slots, like I said (so you can have the null-terminator, which is the zero-valued character, so we don’t need to set it explicitly). Combine that with theoption_string[j]indexing mode, include the missingstdlib.hforcalloc(you should have had it formalloc, too), and we’re good to go!