提问人:amongst3r 提问时间:11/12/2022 最后编辑:amongst3r 更新时间:11/12/2022 访问量:35
如何将指针分配给字符串并使用该指针对其进行修改?
How do I assign a pointer to a string and modify it using said pointer?
问:
假设我有一组结构,它们被定义为
typedef struct myS
{
int content;
char *string;
} myT;
我想通过指针更改第 0 个元素字符串的值,这样就不必直接通过结构访问它。
我所做的如下:
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
int
*int
printf("%s %s ", tArray[0].string, *pString);
tArray[0].string = "hi";
printf("%s %s", tArray[0].string, *pString);
>hello hello hi hello
我真的不明白为什么仍然指向这里。pString
"hello"
有没有办法通过另一个变量修改结构的值?
答:
0赞
etsuhisa
11/12/2022
#1
您期待以下结果吗?
hello hello hi hi
然后,将 的地址设置为如下:.string
pString
#include <stdio.h>
#include <stdlib.h>
int main()
{
typedef struct myS
{
int content;
char *string;
} myT;
myT *tArray;
char **pString;
tArray = malloc(sizeof(myT));
tArray[0].string = "hello";
//pString = malloc(sizeof(char *));
//*pString = tArray[0].string;
pString = &tArray[0].string;
printf("%s %s ", tArray[0].string, *pString);
tArray[0].string = "hi";
printf("%s %s", tArray[0].string, *pString);
return 0;
}
评论
*pString
pString
tArray[0].string
tArray[0].string = "hi";
tArray[0].string
tArray[0].string
hello
.string
pString = .string
hello
pString
.string
"hello"
.string
"hi"
pString
malloc
strcpy
.string
pString
.string