tobecalt
tobecalt

Reputation: 11

How to change the size of a struct using malloc

I am making a struct with undefined size.

#define namemax 128
struct Image{
  char name[namemax+1];
  int length;
  double *array;          //double array[256]
};
  struct Image* graph;

  graph=malloc(max*sizeof(struct Image));

If I define array[256], everything work fine. but if I use double *array, and then write

graph[check].array = malloc( 100 * sizeof(double *));

it creates a segment fault. I was wondering how can I define the size using malloc and realloc for array. If I add value in the array, it shows segment fault.

struct Image* graph;//outside the while loop
while:  //it is inside the while loop  
        //basically it read different name each line, and put the x and y to the array
        graph[check].array = malloc( 100 * sizeof(double));
	    check++;
	    strcpy( graph[check].name,type);
	    graph[check].array[count]=shiftX;
	    graph[check].array[count+1]=shiftY;

Upvotes: 0

Views: 251

Answers (3)

user4710450
user4710450

Reputation:

i think it makes seg fault because in malloc you have said sizeof(double *) (Actually you declare an array of array). Just try to say sizeof(double) it may work but I dont know that for sure because I haven't tested it.

And by the way when you declare array staticly you reserve space for it when you declare your struct variable but when you declare it as pointer ( dynamic array ) you should reserve space for it and you can change the array's size. You should use realloc google it.

Upvotes: 0

Lukas Steiblys
Lukas Steiblys

Reputation: 76

One problem I see is using sizeof(double *) instead of sizeof(double) even if both are the same if you're using x86-64 architecture.

Upvotes: 0

Jim Nutt
Jim Nutt

Reputation: 1756

That because double * array is declaring a pointer to an array, not storage. You want to declare storage here. The easiest way is to simply define the array as double array[1] and make sure it's the last element in the struct. You can then allocate space for the structure using malloc() and realloc() by passing them the size of the base struct plus the size of the array (sizeof double * the number of array elements).

Upvotes: 2

Related Questions