通过C中的指针将值分配给结构中的变量

时间:2012-04-22 22:27:38

标签: c algorithm struct

好的,所以我确定有一个简单的解决方法,我错过了,但是现在我的代码在“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;
}

4 个答案:

答案 0 :(得分:2)

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

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

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

注意:如果指针的typedef混淆了你,请不要使用它;)

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

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

第二个解决方案:如果你想让A [i]成为指针,你必须为指针分配空间(就像你现在一样),然后为每个指针(在循环中)为结构分配空间。

答案 1 :(得分:2)

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

答案 2 :(得分:0)

您的结构名称为Record而不是Item。所以你应该使用sizeof(struct Record)

答案 3 :(得分:0)

这样做:

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