Question

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?

Was it helpful?

Solution 2

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.

OTHER TIPS

There are two problems with your allocations, one is about the memory for the locopt array itself, and the other is about how you allocate memory for des and org in each structure.

First, we don't see if you ever allocate memory for your locopt structure array. If that has L elements, you could do

locopt = calloc(L, sizeof(LOCOPT));

Then, you still need to allocate memory for the fields org and des in it like this (for each structure, as you do), but

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

and likewise for des. LOCOPT is the name of your structure, but the type of your arrays is int.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top