I have a struct
:
typedef struct myStruct {
char** a;
char** b;
} myStruct;
I am trying to read from stdin
and initialize an array of myStruct*
int main() {
int maxlength = 60 + 1;
int arraySize = 2;
myStruct** myArray = (myStruct*) malloc(sizeof(myStruct*) * arraySize);
int runningIndex = 0;
while(1) {
char* aline = (char*) malloc(maxlength);
int status = getline(&aline, &maxlength, stdin);
if(status == -1)
break;
char* bline = (char*) malloc(maxlength);
getline(&bline, &maxlength, stdin);
if(runningIndex == arraySize) {
arraySize *= 2;
myArray = realloc(myArray, sizeof(myStruct*) * arraySize);
}
myArray[runningIndex] = (myStruct*) malloc(sizeof(myStruct*));
myArray[runningIndex]->a = &aline;
myArray[runningIndex]->a = &bline;
runningIndex++;
}
for(int i = 0; i < runningIndex; i++) {
printf("outside the loop at index %d, a is %s and b is %s", i, *myArray[i]->a, *myArray[i]->b);
}
}
I did a few printf
within the while
to confirm that each myStruct
is successfully created with the strings from stdin
. However, outside the loop, all the stored values seems to be gone. I was thinking about scope but could not figure out why. Could someone explain how I shall do this properly? Thanks!