嗨,我遇到了这种情况。我正在使用malloc给我一个包含10个指针的数组。当我在gdb中看到测试指针时,其中一个(第三个)指向0x0。有时,使用apple [2]-> string =“ hello”时,代码会出现段错误。为什么malloc这样做?在此先感谢您的帮助。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int
main(void)
{
typedef struct test
{
char *string;
int data;
} test;
test *apple[10]; // Declare an array of 10 test pointers. This line results in one of the pointers having a null value.
apple[0] = malloc(sizeof(test));
apple[0]->string = "hello";
printf("The string is %s\n",apple[0]->string);
printf("Size of apple[0]->data is %d\n",sizeof(apple[0]->data));
printf("Size of tester is %d\n",sizeof(test));
free(apple[0]);
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我想看看指针数组如何工作。我不打算使用所有10个指针。那我只需要分配我需要的东西吗?巧合的是,第三个指针是0x0?
内存仅分配给第一个元素,apple因此仅apple[0]指向有效struct test。
为以下所有元素分配内存apple:
for (int i = 0; i < sizeof(apple) / sizeof(test*); i++)
{
apple[i] = malloc(sizeof(test));
}
Run Code Online (Sandbox Code Playgroud)
需要类似的循环free()。
test.string是一个char*,因此在完成后指向字符串文字是可以的(尽管类型应该是const char*)。如果希望将字符串复制到,则test.string必须malloc()留有空间将其复制到其中free(),以后再复制。