gpt4 book ai didi

c - Malloc 初始化空指针

转载 作者:行者123 更新时间:2023-12-04 12:00:22 25 4
gpt4 key购买 nike

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

}

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

最佳答案

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

apple的所有元素分配内存:

for (int i = 0; i < sizeof(apple) / sizeof(test*); i++)
{
apple[i] = malloc(sizeof(test));
}

free() 需要类似的循环。

test.string 是一个 char*,所以像您所做的那样指向一个字符串字面值是没问题的(虽然类型应该是 const char*)。如果您希望将字符串复制到 test.string,那么您必须在 malloc() 空间中复制并稍后使用 free()

关于c - Malloc 初始化空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8960801/

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