A. Ryan
A. Ryan

Reputation: 3

C Structure variable access

I would like some help accessing the arrays in my struct. My program compiles without any errors, but stalls when I try to change some values in my struct. I'm stumped as to what the problem is, and would greatly appreciate some assistance.

Global struct declaration:

typedef struct Data {
    float timestamp[array_length];
    float azimuth[array_length];
    float distance[array_length];
    float signal_strength[array_length];
} Datain;

Datain *dataptr;

This is were I try to initialize the arrays to what I would like them to be:

for (i = 0; i <  array_length; i++)
{
    dataptr->timestamp[i]=-100;
    dataptr->distance[i]=-100;
    dataptr->azimuth[i]=-100;
    dataptr->signal_strength[i]=-100;
}

Let me know what you think

Upvotes: 0

Views: 55

Answers (1)

Pablo
Pablo

Reputation: 13580

dataptr is an uninitialized pointer, it's pointing to nowhere. You have to allocate memory for it:

dataptr = malloc(sizeof *dataptr); // or malloc(size * sizeof *dataptr)
                                   // for allocating size Datain objects
if(dataptr == NULL)
{
    // error handling
    // do not continue
}

for(i=0;i<array_length;i++)
{
    dataptr->timestamp[i]=-100;
    dataptr->distance[i]=-100;
    dataptr->azimuth[i]=-100;
    dataptr->signal_strength[i]=-100;
}

/*
   or if you do the malloc(size * sizeof *dataptr)

for(size_t i = 0; i < size; ++i)
{
    for(size_t j = 0; j < array_length; ++j)
    {
        dataptr[i].timestamp[j]=-100;
        dataptr[i].distance[j]=-100;
        dataptr[i].azimuth[j]=-100;
        dataptr[i].signal_strength[j]=-100;
    }
}
*/

and later you don't have to forget to free the memory with

free(dataptr);

And if dataptr is meant to be a single object, then you don't need to declare it as a pointer:

Datain dataptr; // no * here

then later in a function

for(i=0;i<array_length;i++)
{
    dataptr.timestamp[i]=-100;
    dataptr.distance[i]=-100;
    dataptr.azimuth[i]=-100;
    dataptr.signal_strength[i]=-100;
}

and here you don't need to free the memory.

Upvotes: 0

Related Questions