在 C89 中,我似乎无法从现有的字符数组中创建一个字符数组

In C89, I can't seem to make a character array from an existing one

所以我的代码在 buffer[i] = envp[i] 处崩溃了。

我想创建一个 char** 环境变量缓冲区,并将它们设为小写(尚未添加 putc(tolower()) 循环)。但是当我只是尝试使 buffer[i] = envp[i] 时,编译器 returns 我这个错误:

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;

}

请帮忙,我一直在这里伤脑筋:(。非常感谢!!!

char * envp[] 是指向字符的指针数组,而不是字符数组。指针(envp[i])是一个整数。当您尝试将其分配给 buffer[i](这是一个字符)时,您会收到警告。

buffer 不是保存字符串数组的正确类型。应该定义为:

char **buffer;

此外,您应该malloc如下:

buffer = malloc(i * sizeof(*buffer));

明确使用 sizeof(*buffer) 而不是幻数 8,因为不能保证指针是 8 个字节。这也优于 sizeof(char *),因为它不依赖于 buffer 的类型 此外,don't cast the return value of malloc.

由于 env 由 NULL 指针终止,因此您需要对 buffer 执行相同的操作。您还应该使用 strdup 复制字符串,而不仅仅是复制指针,这样您就可以处理单独的副本:

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;

感谢大家的反馈,在这里评论后我能够修复我的功能。为帮助干杯!!!

char **lower_env(int argc, char *argv[], char * envp[])
{
    int i = 0;
    int k = 0;
    int length = 0; /*Going to dictate lengths later on*/
/*creating the double buffer*/
char **buffer;

/* Finding the amount of elements in the environment array*/
while (envp[i])
{
    i++;
}

/* Allocate the memory for the Buffer to hold that amount of elements*/
buffer = calloc(i+1, (sizeof(char*)));


for (i = 0; envp[i] ; i++)
{

    length = strlen(envp[i]); /*Finding the length of each array pointed
                                at by the original environment array*/

    buffer[i] = calloc(length+1 , sizeof(char)); /*Allocating that memory space
                                                        within our buffer array*/


    /*copying over the arrays in lowercase pointed at by the env array to a new memory location
        pointed at by our new buffer array*/
    for (k = 0; k != length; k++)
    {
        buffer[i][k] = tolower (envp[i][k]);
    }
}

return buffer;
}