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

C语言:如何通过指针修改结构体成员的字符串指针指向?

问题与解答:通过指针修改结构体的字符串成员

问题描述

定义如下结构体:

typedef struct myS
{
    int content;
    char *string;
} myT;

想要通过指针修改第0个元素的string成员而非直接访问结构体,尝试了以下代码:

myT *tArray;
char **pString;

tArray = malloc(sizeof(myT));
tArray[0].string = "hello";
pString = malloc(sizeof(char *));
*pString = tArray[0].string;

原本以为pString指向tArray[0].string后,修改tArray[0].string会同步反映到*pString上,但测试代码:

printf("%s %s ", tArray[0].string, *pString);
tArray[0].string = "hi";
printf("%s %s", tArray[0].string, *pString);

输出结果为:

hello hello hi hello

疑惑为何pString仍指向"hello",想知道是否有办法通过其他变量修改结构体的该成员。

解答

你的代码问题在于:*pString = tArray[0].string只是把tArray[0].string当前存储的**"hello"的地址**复制给了*pString,而非让pString指向tArray[0].string这个成员本身。当你执行tArray[0].string = "hi"时,只是把tArray[0].string里的地址换成了"hi"的地址,但*pString里存的还是原来"hello"的地址,自然不会同步变化。

要实现通过指针同步修改结构体的string成员,你需要让pString直接指向tArray[0].string这个成员的内存地址,而不是复制它的值。具体做法如下:

myT *tArray;
char **pString;

tArray = malloc(sizeof(myT));
tArray[0].string = "hello";
// 直接让pString指向tArray[0].string的地址,无需malloc
pString = &tArray[0].string;

此时测试代码:

printf("%s %s ", tArray[0].string, *pString);
// 通过pString修改结构体成员
*pString = "hi";
printf("%s %s", tArray[0].string, *pString);

输出会是:

hello hello hi hi

反过来,如果你修改tArray[0].string,*pString也会同步更新:

tArray[0].string = "hey";
printf("%s %s", tArray[0].string, *pString); // 输出 hey hey

这样就实现了通过外部指针变量同步访问和修改结构体的string成员。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.13 09:55:18