Final versie voor de liefhebbers.
Het doet niet veel maar laat de proof of concept zien.
( het kan nog anders , ik weet het... maar dit is overzichtelijk voor mij.)
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
#include<string.h>
typedef struct {
char * first;
char* second;
} myStruct;
int MAX = 1;
int main(int argc , char **argv){
if (argc == 2) {
printf("argc = %d, argv[1] = %s\n",argc,argv[1]);
MAX = atoi(argv[1]); // non-integer = 0 ;)
}else{
printf("usage %s <number>\n",argv[0]);
return (1);
}
// next malloc space needs to be freed on exit
myStruct** myStructs = (myStruct**)malloc(1*sizeof(myStruct*));
myStruct* thisStruct;
char *myString, tmpString[1024];
int i;
for( i = 0 ; i < MAX ; i++ ){
// expand space for the pointer to array of pointers
myStructs = (myStruct**)realloc(myStructs, (i+1)*sizeof(myStruct*));
// next malloc space needs to be freed on exit
thisStruct = (myStruct*)malloc(sizeof(myStruct));
// next malloc space needs to be freed on exit
sprintf(tmpString,"string-1 %d",i);
myString = (char*)calloc(strlen(tmpString)+1,1);
strcpy(myString, tmpString);
thisStruct->first = myString;
// next malloc space needs to be freed on exit
sprintf(tmpString,"string-2 %d",i);
myString = (char*)calloc(strlen(tmpString)+1,1);
strcpy(myString, tmpString);
thisStruct->second = myString;
myStructs[i] = (myStruct*)thisStruct;
printf("first0 -- %s\nsecond0 - %s\n",
myStructs[0]->first,myStructs[0]->second);
printf("first -- %s\nsecond - %s\n",
myStructs[i]->first,myStructs[i]->second);
}
printf("=================================\n");
for( i = 0 ; i < MAX ; i++ ){
printf("first -- %s\nsecond - %s\n",
myStructs[i]->first, myStructs[i]->second);
}
// free all [c|m]alloc space
for ( i = 0 ; i < MAX ; i++ ){
free( myStructs[i]->first); // members
free( myStructs[i]->second);
free( myStructs[i] ); // ponter to struct
}
free( myStructs); // pointer to struct-pointers
// even now, free space seems draining.... sometimes.
}
sla op als b.v.i : struct2.c
compile - run slag , b.v. : cc -g -o struct2 struct2.c && ./struct2 10000; echo $?