Have to create an array of struct. Since don't know how many entries will have in the array, have to use dynamic array.
Did not worked as advised here - https://stackoverflow.com/a/8455125/1090944.
Having troubles with passing array of struct to function for allocation.
Here is the code:
#include<stdio.h>
#include<stdlib.h>
struct record
{
char * community_name;
double data[10];
double crimes_per_pop;
};
void allocate_struct_array(struct record * array, int length);
int main()
{
int num_lines = 10;
struct record ** data_array;
allocate_struct_array(&data_array, num_lines);
data_array[0]->community_name[0] = 'h';
printf("%c\n", data_array[0]->community_name[0]);
return 0;
}
void allocate_struct_array(struct record * array, int length)
{
int i;
*array = malloc(length * sizeof(struct record *));
if (!array)
{
fprintf(stderr, "Could not allocate the array of struct record *\n");
exit(1);
}
for (i = 0; i < length; i++)
{
array[i] = malloc( sizeof(struct record) );
if (!array[i])
{
fprintf(stderr, "Could not allocate array[%d]\n", i);
exit(1);
}
array[i]->community_name = malloc(100 * sizeof(char));
}
}
Here are errors and warnings that I got from the compiler:
../src/temp.c: In function 'main':
../src/temp.c:19: warning: passing argument 1 of 'allocate_struct_array' from incompatible pointer type
../src/temp.c: In function 'allocate_struct_array':
../src/temp.c:32: error: incompatible types in assignment
../src/temp.c:42: error: incompatible types in assignment
../src/temp.c:44: error: wrong type argument to unary exclamation mark
../src/temp.c:50: error: invalid type argument of '->'
make: *** [src/temp.o] Error 1