I know there are multiple questions about creating dynamic arrays in C but they didn't really help me so let me ask in a different way.
My program needs to read in a variable number of command line arguments, each of variable length. This function takes the argv array passed into main and should return an array of char* containing only those arguments that are environment settings. (The program needs to replicate the UNIX env command.) Here is what I have now:
char** getEnvVariables(char* args[], int start) {
int i = start;
char** env_vars = (char **) malloc(1);
while (args[i]) {
printf("size of env_vars: %d\n", sizeof(env_vars));
if (isEnvironmentSetting(args[i])) {
printf("arg: %s\n", args[i]);
printf("size of arg: %d\n", sizeof(args[i]));
printf("new size of env_vars: %d\n", (sizeof(env_vars) + sizeof(args[i])));
env_vars = realloc(env_vars, (sizeof(env_vars) + sizeof(args[i])));
memcpy(env_vars, args[i], sizeof(args[i]));
i++;
}
else
break;
}
return env_vars;
}
My idea was to create the array with malloc() and then use realloc() to allocate the space needed for each char* and memcpy() to add the new char* to the array. But the array isn't actually growing. At each iteration of the loop, it's size is 8 bytes. I'm still very new to C and the hands-on memory management so any help is appreciated.
sizeof(...)is a compile-time construct (except in the case of VLAs, which you don't need to worry about here), sosizeof(env_vars)is the size of the pointerenv_vars, not the size of the block of allocated memory thatenv_varspoints to. There is no portable way to determine the latter; you just have to keep track yourself of the value that you pass tomalloc/realloc.sizeofis also notstrlen, sosizeof(args[i])is also wrong.