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

C语言修改指向指针的指针:为何字符串指向未变更?

问题:修改char*指针指向新字符串后,打印原数组仍输出旧值?

我尝试编写一个接收char**类型参数的void函数,目的是修改原char*指针,使其指向新字符串"hello"。以下是我编写的代码:

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

void change_ptr(char **str_ptr)
{
    char hello[] = "hello";
    char *hello_ptr = hello;
    *str_ptr = hello_ptr;
}

int main()
{
    char str[] = "yay";
    char *str_ptr = str;
    char **ptr_to_str_ptr = &str_ptr;
    change_ptr(ptr_to_str_ptr);
    printf("%s\n", str);

    return 0;
}

运行代码后,最终打印str时仍输出"yay",调试打印地址时看似一切正常,请问我哪里出错了?


解答

你的代码存在两个关键问题:

1. 局部数组的生命周期问题

函数change_ptr里的char hello[] = "hello";是局部自动变量,它存储在栈内存中,当函数执行完毕返回后,这块栈内存会被系统回收,此时*str_ptr(也就是main里的str_ptr)指向的是一块已经无效的内存,属于野指针。后续访问这块内存的行为是未定义的,哪怕调试时地址看似正常,实际内存内容已经不可靠。

2. 打印对象错误

你在main中打印的是str,这是一个栈上的字符数组,它的内容不会因为你修改str_ptr的指向而改变。你真正修改的是str_ptr这个指针的指向,所以应该打印str_ptr而不是str。


修正后的代码示例

方案一:使用字符串字面量(适合只读字符串)

字符串字面量存储在程序的只读数据段,生命周期贯穿整个程序运行过程:

#include <stdio.h>

void change_ptr(char **str_ptr)
{
    *str_ptr = "hello";
}

int main()
{
    char str[] = "yay";
    char *str_ptr = str;
    change_ptr(&str_ptr);
    // 打印修改后的指针指向的内容
    printf("%s\n", str_ptr);

    return 0;
}

方案二:动态分配内存(适合需要修改的字符串)

如果需要后续修改字符串内容,可以用malloc动态分配内存,注意使用完后要手动释放:

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

void change_ptr(char **str_ptr)
{
    char *hello = malloc(strlen("hello") + 1);
    if (hello != NULL) {
        strcpy(hello, "hello");
        *str_ptr = hello;
    }
}

int main()
{
    char str[] = "yay";
    char *str_ptr = str;
    change_ptr(&str_ptr);
    printf("%s\n", str_ptr);
    // 释放动态分配的内存,避免内存泄漏
    free(str_ptr);

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 03:25:32