Malloc初始化空指针

Malloc初始化空指针,c,malloc,C,Malloc,嗨,我遇到了这种情况。我使用malloc给我一个10个指针的数组。当我在gdb中看到测试指针时,其中一个(第三个)指向0x0。使用apple[2]->string=“hello”时,有时代码会出错。为什么malloc会这样做?提前谢谢你的帮助 #include <stdio.h> #include <stdlib.h> #include <string.h> int main(void) { typedef struct test {

嗨,我遇到了这种情况。我使用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;

 }
#包括
#包括
#包括
int
主(空)
{
类型定义结构测试
{
字符*字符串;
int数据;
}试验;
test*apple[10];//声明一个由10个测试指针组成的数组。此行将导致其中一个指针具有空值。
苹果[0]=malloc(sizeof(test));
苹果[0]->string=“你好”;
printf(“字符串是%s\n”,苹果[0]->string);
printf(“苹果[0]->数据的大小为%d\n”,sizeof(苹果[0]->数据));
printf(“测试仪的大小为%d\n”,大小为(测试));
免费(苹果[0]);
返回0;
}

我想看看指针数组是如何工作的。我不打算使用所有的10个指针。那么,我是否只需要满足我的需求?第三个指针是0x0,这是巧合吗?

内存只分配给
apple
中的第一个元素,因此只有
apple[0]
指向有效的
struct test

要为apple的所有元素分配内存,请执行以下操作:

for (int i = 0; i < sizeof(apple) / sizeof(test*); i++)
{
    apple[i] = malloc(sizeof(test));
}
for(inti=0;i
free()
需要类似的循环

test.string
是一个
char*
,所以像您所做的那样指向字符串文本是可以的(尽管类型应该是
const char*
)。如果要将字符串复制到
test.string
中,则必须
malloc()
空间才能复制到该字符串中,并且
free()
以后将其复制到该字符串中。

您只分配了
test
的一个实例,并将其分配给第一个数组元素:

apple[0] = malloc(sizeof(test));
要分配全部10个,您需要执行以下操作:

for (int i = 0; i < 10; i++) {
    apple[i] = malloc(sizeof(test));
}
for(int i=0;i<10;i++){
苹果[i]=malloc(sizeof(test));
}

根据您的最终目标,有不同的方法

如果每次运行程序时数组中的元素数都是恒定的,则根本不必使用指针:

test apple[10]; // array with 10 instances of test

test[0].string = ...;
test[1].data = ...;
如果您想使用您的方法(使用指针,目前还没有必要使用指针),则必须单独使用malloc()每个元素(就像您使用
apple[0]
或malloc()整个数组所做的那样):

int num = 10;
test *apple = malloc(sizeof(test) * num);

// access any element here
apple[5].string = "hello!";

free(apple);

是的,未初始化的内存可以保存任何值。只有
malloc()
您需要什么,但您需要一种方法来知道您有什么malloc,将所有未分配的元素设置为
NULL
,例如:
test*apple[10]={0};