我在StackOverflow上搜索了所有内容,但找不到我想要做的事情。我想将指针项目复制到指针 COPYTO。然后能够调用 COPYTO->x。
#include <stdio.h>
typedef struct JustArray {
char x[30];
} JustArray;
int main()
{
JustArray *Items, *COPYTO;
char d[10] = "Test";
Items = malloc(sizeof(Items));
COPYTO = malloc(sizeof(COPYTO));
strcpy(&Items->x,d);
memmove(©TO, Items, sizeof(JustArray));
printf("Pointer: %pn", &d);
printf("Address: %un",&d);
printf("Value: %sn", Items->x);
printf("Value: %sn", COPYTO->x);
return 0;
}
此程序可编译,但不会运行。它有一个弹出窗口说:访问违规读取位置0xabababab。
我来自 C#,发现 C 非常难以理解......
最大的问题是这一行:
memmove(©TO, Items, sizeof(JustArray));
COPYTO
是一个指针。您使用malloc
分配了内存并保存了 这段记忆要COPYTO
.此地址是您想要的目标。
&
运算符返回变量的地址,©TO
返回COPYTO
变量的地址,而不是它指向的位置。
正确版本:
memmove(COPYTO, Items, sizeof(JustArray));
另一个问题是你称呼malloc
的方式:
Items = malloc(sizeof(Items));
COPYTO = malloc(sizeof(COPYTO));
sizeof(expression)
返回expression
的字节数 内存中的需求。sizeof(Items)
返回指针的字节数 需要(因为Item
是一个指针),而不是JustArray
对象需要的字节数。
正确版本:
Items = malloc(sizeof *Items);
COPYTO = malloc(sizeof *COPYTO);
请记住,检查malloc
和 朋友。如果它们返回NULL
,则没有更多可用内存,您应该 执行一些错误处理。
此外,对于每个malloc
都必须有一个free
.在printf
结束时, 请做:
free(Items);
free(COPYTO);
strcpy(&Items->x,d);
你可以像这样重写:
strcpy(Items->x, d);
原因是数组在将它们传递给函数时会衰减为指针,并且 将它们分配给指针。"衰减"意味着它返回 数组的第一个元素。
对于以下数组
char line[] = "Hello World";
这些是等效的:
char *ptr1 = &line[0];
char *ptr2 = &(line[0]);
char *ptr3 = line;