So my code breaks down at buffer[i] = envp[i].
I want to create a char**buffer of the environment variables, and make them lower case (didn't add the putc(tolower()) yet loop). But when I just try to make buffer[i] = envp[i], the compiler returns me this error:
error: assignment makes integer from pointer without a cast [-Wint-conversion] buffer[i] = envp[i]; ^
warning: format ‘%s’ expects argument of type ‘char *’, but argument 2 has type ‘int’ [-Wformat=] printf("%s\n", buffer[i]); ~^ ~~~~~~~~~ %d
int main(int argc, char *argv[], char * envp[])
{
int i = 0;
char *buffer = NULL;
while(envp[i])
{
i++;
}
buffer = (char *)malloc(i * 8);
for (i = 0; envp[i] != 0 ; i++)
{
buffer[i] = envp[i];
printf("%s\n", envp[i]);
printf("%s\n", buffer[i]);
}
return 0;
}
Please help, I've been breaking my head here :( . Thanks so much!!!
buffer
is not the correct type to hold an array of strings. It should be defined as:
char **buffer;
Also, you should malloc
as follows:
buffer = malloc(i * sizeof(*buffer));
Use sizeof(*buffer)
explicitly instead of the magic number 8, as a pointer is not guaranteed to be 8 bytes. This is also prefered to sizeof(char *)
as it does not depend on the type of buffer
Also, don't cast the return value of malloc
.
Since env
is terminated by a NULL pointer, you'll want to do the same with buffer
. You should also copy the strings with strdup
instead of just copying the pointers so you can work on a separate copy:
char **buffer = malloc((i+1) * sizeof(*buffer));
for (i = 0; envp[i] != 0 ; i++)
{
buffer[i] = strdup(envp[i]);
printf("%s\n", envp[i]);
printf("%s\n", buffer[i]);
}
buffer[i] = NULL;