Mary Poppins
Mary Poppins

Reputation: 79

I cannot read a structure in another one in c language

I am trying to read a structure which contains another structure and then write it in a binary file. However, when i check if the structure was well read from the keyboard, the structure FIRMA is not read correctly. The value of 'nrang' is always 0 and the 'localitate' string is something very odd. This is my code:

#include <stdio.h>
#include <stdlib.h>


typedef struct
{
    char localitate[10];
    int nrang;
} FIRMA;

typedef struct
{
    char nume[20];
    int varsta;
    FIRMA firma;
} ANG;


int main()
{
    FILE* f;
    ANG* a;
    int n,i;
    if ((f=fopen("fis.txt","wb"))==NULL) exit(1);
    printf("number?\n");
    scanf("%d",&n);
    a=(ANG*)malloc(n*sizeof(ANG*));
    printf ("Dati valorile");
    for (i=0; i<n; i++)
    {
        scanf("%s%d",&a[i].nume,&a[i].varsta);
        scanf("%s",&a[i].firma.localitate);
        scanf("%d",&a[i].firma.nrang);
        fwrite(&a[i],sizeof(a[0]),1,f);
        printf("%s\n%d\n%s\n%d\n",a[i].nume,a[i].varsta,a[i].firma.localitate,a[i].firma.nrang);

    }



}

Upvotes: 0

Views: 71

Answers (1)

manveti
manveti

Reputation: 1711

Note that sizeof(ANG*) is not the same as sizeof(ANG) (the former is the size of the pointer -- probably 8 -- whereas the latter is the size of the structure -- probably 40), which means you're only allocating about 1/5 of the memory you intend to. As a result, the later code winds up writing and reading past the end of what's been allocated, which has undefined behavior.

One practice that helps people with this is to get into the habit of using sizeof(*ptr) when allocating for a pointer ptr, which will always give you the size of what it points to so you don't have to think of "do I need sizeof(ANG) or sizeof(ANG*) here?". This is particularly useful when allocating multi-dimensional arrays (e.g. int ***three_d_array = malloc(n * sizeof(*three_d_array))).

Upvotes: 3

Related Questions