I know I can initialize an array of strings this way:
static const char *BIN_ELEMENTS[5] = {
"0000\0", // 0
"0001\0", // 1
"0010\0", // 2
"0011\0", // 3
"0100\0", // 4
};
But I need to accomplish that in a dynamic way. Reading the characters from a File, and inserting them into an array. Then copy that array into an array of strings (like above).
So let's say I captured the following chars from a File, and inserted them into an array, like these:
char number[5];
char *listOfNumbers[10];
number[0]='1';
number[1]='2';
number[2]='3';
number[3]='4';
number[4]='\0';
Now I would like to copy the whole content of number, into listOfNumers[0]
// meaning that I've stored "1234" in position 0 of listOfNumers. Leaving 9 more positions to store different numbers.
So I would do something like this:
listOfNumers[0] = number; //this actually seems to work.
But since its a huge file of numbers, I need to reuse the array number, to extract a new number. But when I do that, the content previously stored in listOfNumers[0] gets overwritten, eventho I updated the new position for the new number. How can I deal with that?
Here is what I have so far:
char number[5]; // array for storing number
int j=0; // counter
int c; // used to read char from file.
int k=0; // 2nd counter
char*listOfNumbers[10]; // array with all the extracted numbers.
FILE *infile;
infile = fopen("prueba.txt", "r");
if (infile) {
while ((c = getc(infile)) != EOF) {
if(c != ' ' && c != '\n')
number[k] = c;
++k;
} // end inner if
else {
number[k] = '\0';
listOfNumbers[j] = number;
printf("Element %d is: %s\n", j, listOfNumbers[j]); // prints correct value
++j;
k=0;
} // end else
} // end while
fclose(infile);
} // end outer if
printf("\nElement 0 is: %s\n", listOfNumbers[0]); // fails - incorrect value
printf("Element 1 is: %s\n", listOfNumbers[1]); // fails - incorrect value
printf("Element 2 is: %s\n", listOfNumbers[2]);