我是否以正确的方式返回双字符?

Am I returning double char the correct way?

我目前正在练习 malloc 并尝试在 c 中创建一个字符串数组。 以下是我的小程序:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int read_arguments(char*s[]);
char** copy_argv(char*s[]);
void free_char_ary(char*s[]);
int main(int argc, char* argv[])
{
    int count = read_arguments(argv);
    
    char **arr = copy_argv(argv);
    for(int i = 0; i < count; i++)
    {
        printf("%s\n", arr[i]);
    }

    free_char_ary(arr);
    exit(0);
}

int read_arguments(char*s[])
{
    int count = 0;
    
    while(*s) 
    {
        count++;
        s++;
    }
    
    return count;
}


char** copy_argv(char*s[])
{
    int result = read_arguments(s);
    printf("result = %d\n", result);
    char** ary = (char**) malloc(result * sizeof(char*));
    for(int i = 0; i < result; i++)
    {
        ary[i] = (char*) malloc(100 * sizeof(char));
        strcpy(ary[i], s[i]);        
    } 
    return ary;
}

void free_char_ary(char*s[])
{
    int count = read_arguments(s);
    printf("count = %d\n", count);
    for(int i = 0; i < count; i++)
    {
        free(s[i]);
    }
    free(s);
}

结果很奇怪。如果我执行 4 个参数,那很好,但如果我执行 5 个参数,那么我会在 free_char_ary 处出现分段错误。我发现read_arguments返回的int在icopy_argv到char**arr之后是不一样的。我是否以正确的方式使用双字符指针?为什么结果不同?

函数 free_char_ary 具有未定义的行为,因为动态分配的数组不包含值为 NULL 的元素。结果,在函数内调用 read_arguments 会调用未定义的行为。

void free_char_ary(char*s[])
{
    int count = read_arguments(s);
    printf("count = %d\n", count);
    for(int i = 0; i < count; i++)
    {
        free(s[i]);
    }
    free(s);
}

您应该像定义数组 argv 一样用空指针附加动态分配的数组。或者您可以将动态分配数组中元素的实际数量传递给函数,