views:

521

answers:

2

I am working on a project using C. I store several records in a two-dimensional array of strings, where one string is the record name and the other string is the actual value. For example:

myArray[0][0] = "filename1";
myArray[0][1] = "somefile.txt";
myArray[1][0] = "filename2";
myArray[1][1] = "anotherfile.txt";
// and so on ...

I know how to store the values in the array, but I'm not sure how to print them out. Can you please help me figure it out?

+4  A: 

try if you are working with a 2d array chars (ie 1d array of strings)

your_2d_array[0] = "file_name_1" /* and so on ... */


for( i = 0 ; i < num_of_file_names ; i++ )
{
    printf("%s\n", your_2d_array[i]);
}

If you are working with a 2d array of strings (ie 3d array of chars) as the edit seems to indicated then simply do the following

for( i = 0; i < num_of_file_names ; i++ )
{
    printf("%s : %s \n", your_2d_array[i][0], your_2d_array[i][1] );
}
hhafez
Well, that's a 1d array for a start, but I'm not going to mod you down since I didn't understand the question.
paxdiablo
A 2d array of characters is a 1d array of c-strings, so I think that would work.
drhorrible
@Pax I assumed the questioner meant a 2d array of chars, from the initial version of the question it wasn't clear what was meant by a 2d array. I've added an alternative answer based on the edit by eJames
hhafez
No probs, made minor fix to array index, then +1, good answer.
paxdiablo
@hhafez: I didn't even consider the fact that a 1D array of char * could be interpreted as a 2D array of type char. +1 from me, too.
e.James
+2  A: 

I would go with the following:

int recordIndex;
for (recordIndex = 0; recordIndex < num_records; recordIndex++)
{
    printf("%s: %s\n", myArray[recordIndex][0], myArray[recordIndex][1]);
}

Which will output as follows:

filename1: somefile.txt
filename2: anotherfile.txt
...
e.James