gpt4 book ai didi

c - 如何将字符串赋值给 char* 指针?

转载 作者:行者123 更新时间:2023-12-05 04:12:48 24 4
gpt4 key购买 nike

#include <stdio.h>

struct Analysis {
int lnlen;
int arr[2];
char* name;
};

int main()
{
struct Analysis ana_space[2];
char *ptr = (void*) &ana_space;

ana_space[0].lnlen = 0;
ana_space[0].arr[0] = 1;
ana_space[0].arr[1] = 2;
ana_space[0].name = "Peter";

printf("\n%d\n", *ptr); // print 0;

*ptr = 10; // how to use memcpy here;

printf("\n%d\n", *ptr); // print 10;

ptr = ptr + sizeof(int); // advance pointer by int;

printf("\n%d\n", *ptr); // print 1;

ptr = ptr + 2*sizeof(int); // advance pointer by 2 ints;

printf("\n%s\n", *ptr); // print "Peter"; --------------not work

//*ptr = "Jim"; // how to assign new name "Jim" into that memory;
return 0;
}

输出:

0

10

1

(null)

我想使用 char * 作为指针来遍历内存地址以获取一些数据并将值存储到内存中。

对于 int 和 int array,它工作正常,但不适用于字符串。

如何打印字符串并将新的字符串值存入内存?

最佳答案

您的方法不可移植。使用offsetof会更好以确保您可以可靠地指向 struct 成员的地址。

int main()
{
struct Analysis ana_space[2];
char *ptr = (void*) &ana_space;

size_t offset1 = offsetof(struct Analysis, arr);
size_t offset2 = offsetof(struct Analysis, name);

ana_space[0].lnlen = 0;
ana_space[0].arr[0] = 1;
ana_space[0].arr[1] = 2;
ana_space[0].name = "Peter";

// advance pointer to point to arr.
ptr = ptr + offset1;

// advance pointer to point to name
ptr = ptr + (offset2-offset1);

// Cast the pointer appropriately before dereferencing.
printf("\n%s\n", *(char**)ptr);

// how to assign new name "Jim" into that memory;
*(char**)ptr = "Jim";
printf("\n%s\n", *(char**)ptr);

return 0;
}

您的使用:

printf("\n%d\n", *ptr);     // print 0;

*ptr = 10; // how to use memcpy here;

printf("\n%d\n", *ptr); // print 10;

并且预期的输出是有缺陷的。它只适用于小端系统。我建议使用:

printf("\n%d\n", *(int*)ptr);

*(int*)ptr = 10;

printf("\n%d\n", *(int*)ptr);

关于c - 如何将字符串赋值给 char* 指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39422184/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com