#include <stdio.h>
#include<string.h>
#include<stdlib.h>
int main()
{
char *words[] = {"mHello", "kWorld", "kHow", "9Are", "3You?"};
char **parsed = malloc(5);
int i;
for (i = 0; i < 5; i++)
{
int n = strlen(words[i]);
parsed[i] = malloc(n);
strncpy(parsed[i], words[i] + 1, n);
printf("[%s] ", parsed[i]);
}
printf("\n----------------------\n");
for (i = 0; i < 5; i++)
printf("[%s] ", parsed[i]);
return 0;
}
parsed[i] contains words[i] without the first character.
The output is
[Hello] [World] [How] [Are] [You?]
----------------------
[▒▒ o] [World] [How] [Are] [You?]
Why does the first printf call to parsed[0] work correctly while the second one doesn’t ?
Also, if I remove one element from words, this code works correct. What is going on ?
Your
mallocis not allocating the correct space for pointers to strings though, it should be