为什么我的 char 数组返回 null 值?[复制]

Why are my char arrays returning a null value? [duplicate]

提问人:Connor 提问时间:5/15/2023 更新时间:5/15/2023 访问量:49

问:

我正在尝试编写一个函数,该函数将值读取到指针数组中以存储可变长度的字符串。字符串似乎正确存储在 中,但在 main 函数中打印时具有 null 值。请参阅下面的代码:get_input

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void get_input(char *ptr)
{
    ptr = calloc(50, sizeof &ptr);
    printf("Type something: ");
    fgets(ptr, 50, stdin);
    int len = strlen(ptr);
    if (*(ptr + len - 1) == '\n')
        *(ptr + len - 1) = 0;
    printf("%s\n", ptr);
}

int main()
{
    char **string_array = calloc(5, sizeof(char *));
    if (string_array == NULL)
    {
        fprintf(stderr, "Unable to allocate array\n");
        exit(1);
    }

    for (size_t index = 0; index < 5; index++)
    {
        get_input(string_array[index]);
    }

    for (size_t index = 0; index < 5; index++)
    {
        printf("%s\n", *(string_array + index));
    }
}

我做错了什么?为什么字符串没有正确存储?

数组 c 指针 内存 null

评论

1赞 Adrian Mole 5/15/2023
按值传递每个元素。这意味着在函数中发生的任何事情都不会反映在 中。将参数声明为 并传递 .这应该有一个副本......看。。。string_arraymainchar **&string_array[index]
1赞 Adrian Mole 5/15/2023
好的 - 我找到了一个合理的重复项,但如果有人应该找到这样的目标,我很乐意添加更多/更好的目标。

答:

1赞 0___________ 5/15/2023 #1

void get_input(char *ptr) - ptr是一个局部变量,赋值给它不会更改调用它时传递的对象。您需要使用指向指针的指针:

void get_input(char **ptr)
{
    *ptr = calloc(50, sizeof *ptr);
    printf("Type something: ");
    fgets(*ptr, 50, stdin);
    int len = strlen(*ptr);
    if ((*ptr)[len - 1] == '\n')
        (*ptr)[len - 1] = 0;
    printf("%s\n", *ptr);
}

int main()
{
    char **string_array = calloc(5, sizeof(char *));
    if (string_array == NULL)
    {
        fprintf(stderr, "Unable to allocate array\n");
        exit(1);
    }

    for (size_t index = 0; index < 5; index++)
    {
        get_input(&string_array[index]);
    }

    for (size_t index = 0; index < 5; index++)
    {
        printf("%s\n", *(string_array + index));
    }
}

https://godbolt.org/z/dWdK9jdza

评论

0赞 Connor 5/15/2023
好的,所以我分配内存,然后将地址提供给本地指针。但是该地址不会保留在函数之外,因此内存在没有引用的情况下仍然分配?
0赞 0___________ 5/15/2023
@AdrianMole 和 ?你的问题是什么?
0赞 0___________ 5/15/2023
@AdrianMole和......?