繁体   English   中英

通过C中的指针为结构内的变量分配值

[英]Assigning Values to Variables Within Structs Through Pointers in C

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

Item.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;
}

请注意, Item已经是一个指针!

您必须为结构分配空间,而不是为指针分配空间:

A = (Item)malloc(n * sizeof(struct Record));

注意:如果用于指针的typedef使您感到困惑,请不要使用它;)

A[i]->key表示A[i]是一个指针,但是您只是分配了一个数组,因此请使用A[i].key

注意:您必须相应地更改A的类型。

第二种解决方案:如果要让A [i]成为指针,则必须首先为指针分配空间(就像现在所做的那样),然后为每个指针(在循环中)为结构分配空间。

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

您的结构名称是Record not Item 因此,您应该使用sizeof(struct Record)

这样做:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM