gpt4 book ai didi

c - 在 C 中通过指针为结构中的变量赋值

转载 作者:塔克拉玛干 更新时间:2023-11-03 05:39:39 24 4
gpt4 key购买 nike

好的,所以我确定我缺少一个简单的修复程序,但现在我的代码在行“A[i]->key = 0;”上导致了段错误。 Record* Item 部分是程序所必需的,所以我需要让它以这种方式为我正在处理的任务工作,但是如果我确实更改它以便 Item 成为 Record 的非指针 typedef,那么我可以使用 A[i].key 没问题。我只需要朝正确的方向插入,这样我就可以使 standInput 正确地将值分配给指向记录的指针数组。谢谢!

项目.h:

#include "stdio.h"
#include "stdlib.h"

typedef int keyType;

struct Record
{
keyType key;
int other;
};
typedef struct Record* Item;

void standInput(Item *A, int n)
{
int i, input;
for(i = 0; i <= n-1; i++)
{
A[i]->key = 0;
printf("%d ", A[i]->key);
}
}

主要内容:

#include "stdio.h"
#include "stdlib.h"
#include "Item.h"

int main()
{
int n;
Item *A;
printf("Enter a length for the array: ");
scanf("%d", &n);
A = (Item*)malloc(n * sizeof(Item));
standInput(A, n);
return 0;
}

最佳答案

A 中的值都未初始化,但您无论如何都将它们用作 struct Record 指针。如果你想让 A 继续保存指针(而不是直接保存结构),那么你需要为 A 的每个项目分配空间由 A 指向。

关于c - 在 C 中通过指针为结构中的变量赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10272670/

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