You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何char指针数组返回空值?字符串无法正确存储的原因

问题分析与修复

你的代码核心问题在于函数参数传递方式错误,以及内存分配的尺寸计算有误,导致main函数里的指针数组无法正确接收分配的内存地址。

错误点详解

  1. 参数传值导致地址无法回传
    get_input函数的参数是char *ptr,这是值传递——函数内部的ptr只是main函数中string_array[index]的副本。当你在函数里执行ptr = calloc(...)时,只是修改了这个副本的地址,并不会影响main里原指针的值。所以main里的string_array[index]始终是calloc初始化的NULL,打印自然为空。

  2. 内存分配的尺寸错误
    calloc(50, sizeof &ptr)里的sizeof &ptr是取指针地址的大小(也就是指针类型的大小,通常是8字节或4字节),这会导致你分配了远大于实际需要的内存空间。正确的应该是sizeof(char)(或直接写1,因为char的大小固定为1字节)。

修复后的代码

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

// 修改参数为char**,传递指针的地址
void get_input(char **ptr)
{
    // 分配50个char大小的内存并初始化0
    *ptr = calloc(50, sizeof(char));
    if (*ptr == NULL) {
        fprintf(stderr, "Memory allocation failed\n");
        exit(1);
    }
    printf("Type something: ");
    fgets(*ptr, 50, stdin);
    int len = strlen(*ptr);
    if (len > 0 && *(*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]);
    }

    // 释放分配的内存,避免内存泄漏
    for (size_t index = 0; index < 5; index++)
    {
        free(string_array[index]);
    }
    free(string_array);
    return 0;
}

修复说明

  • 将get_input的参数改为char **ptr,让函数可以通过*ptr直接修改main函数里的指针变量;调用时传入&string_array[index],即指针数组元素的地址。
  • 修正calloc的内存尺寸为sizeof(char),确保分配的是符合需求的字符空间。
  • 添加内存分配失败的检查,以及程序结束时的内存释放逻辑,避免内存泄漏。
  • 增加len > 0的判断,防止用户直接输入回车导致strlen返回0,进而出现数组越界访问的问题。

内容的提问来源于stack exchange,提问作者Connor

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.22 03:40:23