I want to create an array of strings called arguments that copies entries from an array of strings called words (from words[1] until the end). I'm having trouble with malloc and don't really understand how much I should malloc. I first sum all the characters in total that I'm going to be storing. The last entry in words is always NULL.
words = ["jargon","hello", "world", NULL];
int sum = 0;
for(int i = 1; words[i] != NULL; i++) {
sum += strlen(words[i]);
}
So i will have sum characters in my array called arguments. So now i malloc and copy the required entries.
char **arguments = malloc(sum * sizeof(char));
for(int i = 0; words[i] != NULL; i++) {
strcpy(arguments[i], words[i+1]);
}
However, i get a memory buffer overflow. If i change it to
char **arguments = malloc(sum * sizeof(*arguments));
I get past the memory buffer overflow but instead am greeted with an uninitialized value in arguments[i] in the next line. Could anyone shed some light on what's going on?
Edit: Sorry about the poor style and thanks for the advice.
words? Please provide a minimal reproducible examplemalloc(sum * sizeof(char))->malloc(sum * sizeof(char*))for(int i = 1;<-- first index of an array is0words[1]is a choice of style rather than function. As stated in the question, it is a functional requirement. Specifically, they are given a pointer, and the required task is to copy fromwords[1]on. This arises naturally when the standardargvofmainis passed to a routine and one desires to copy the arguments but not the program name.