Hi all,
Still not getting my head around multidimentional arrays and was wondering if anyone would be so curtious as to explain what I am doing wrong and why it's wrong. I am trying to read data out of a file and put the information into individual arrays to be displayed on the screen. I also want access to any of the array elements individually.
The code I have thus far:
Code:
/*
Reads a single record from the currently open file into an array of
strings.
A single record is in the format of:
field1,field2,field3,field4
Returns ntokens.
*/
int fileio(char **ptr, int fp)
{
char buffer[BUFSIZ]; // Temp storage for single field.
char **ptr_to_ptr = ptr; // A pointer to the pointer address
// passed to the function.
int i, ntokens = 0;
fseek(file, fp, SEEK_SET); // Seeks to a point in file assigned by fp.
/* Reads the record from currently open file into the array */
if(fgets(buffer, sizeof buffer, file) != NULL)
{
char *sep = strtok(buffer, DELIM); // First call to strtok.
while(sep != NULL)
{
strcpy(*ptr_to_ptr, sep);
sep = strtok(NULL, DELIM); // Second call to strtok using NULL.
ntokens += *ptr_to_ptr[i]; // increments ntokes length of i array.
*ptr_to_ptr += MAXLEN; // increments the pointer the size of array.
i++; num_elements++; // increments local variable i, and global
// variable num_elements.
}
}
return ntokens;
}
This code works fine when called like this
Code:
*ptr_array = &array[0][0];
fileio(ptr_array, fp);
and I can display the whole array
Code:
for(i = 0; i < count; i++)
{
cursor(row, indent); // Positions cursor on the screen.
printf("%s", array[x++]); // Prints contents of the array on the screen.
indent += 8; // Moves the cursor a set distance on the screen.
}
or pick out what I want
Code:
printf("%s", array[27]);
(There is also an annoying 'Null pointer assignment' message displayed that I can't get rid of)
But when I try to recall it like this
Code:
*ptr_array = &array[1][0];
fileio(ptr_array, fp);
it goes downhill fast all that is displayed is random garbage.
I hope I have given you enough information to work with. Thanks to those who reply.