Search code examples
carrayspointersdata-structurescalloc

Data Structure in C with pointers: I want to store an array of information in each position


How can I define a data structure in C, where for each position I want to store: an int array of size M, an int array of size N and a double value? I tried the following with no success yet.

At the beginning of my code I defined my data structure (LOCOPT) as follows:

typedef struct LOCOPT
{
  int    *org;
  int    *des;
  double value;
} LOCOPT;

LOCOPT *locopt;

Then, I initialized the locopt using calloc as follows:

for( locopt_ctr=0 ; locopt_ctr<locopt_max ; locopt_ctr++ )
{
    locopt[locopt_ctr].org = (LOCOPT *) calloc(M, sizeof(LOCOPT));
    locopt[locopt_ctr].des = (LOCOPT *) calloc(N, sizeof(LOCOPT));
}

When I tried to use it in the code it did not work: I want to do this:

for( m=0 ; m<M ; m++ )
locopt[locopt_ctr].org[m] = origin[m]; // regardless of what origin[m] is.

I need to use calloc several times instead of once only and I don't know how to do that. I need to use the loop properly. Any ideas please?


Solution

  • You're trying to do too much at once. Let's break this down to some simpler pieces first:

    1. You've declared LOCOPT *locopt. Before you can use locopt itself as a pointer (or in array syntax) to anything, you have to allocate memory for it, eg

      locopt[locopt_ctr] = (LOCOPT *) calloc(1,sizeof(LOCOPT));

    But that's only part of the effort.

    1. If you want to store a list of items in each instance of locopt, then you need to call calloc again on the members of the newly allocated locopt instance :

      locopt[locopt_ctr].org = (int *) calloc(M, sizeof(int)); locopt[locopt_ctr].des = (int *) calloc(N, sizeof(int));

    Bottom line - if you've got a pointer, you've got to allocate it eventually.