fprint an array of string pointers?

This is a discussion on fprint an array of string pointers? within the C Programming forums, part of the General Programming Boards category; hi,
i'm working on a project that has dynamically allocated strings placed into a dynamically allocated array. i'm trying to ...

fprint an array of string pointers?

hi,

i'm working on a project that has dynamically allocated strings placed into a dynamically allocated array. i'm trying to use fprint to print out all of the strings to standard output, but it's not working too well.

here's my statement:

Code:

fwrite ((char**)rec_arr, sizeof(char*), rec_index, stdout);

rec_arr is a dynamically allocated char** array and rec_index is the number of pointers in rec_arr. using a for-loop seems to work, but i'm not sure if i'm fully utilizing the potential of fwrite. any help would be appreciated!

i'm working on a project that has dynamically allocated strings placed into a dynamically allocated array. i'm trying to use fprint to print out all of the strings to standard output, but it's not working too well.

here's my statement:

Code:

fwrite ((char**)rec_arr, sizeof(char*), rec_index, stdout);

rec_arr is a dynamically allocated char** array and rec_index is the number of pointers in rec_arr. using a for-loop seems to work, but i'm not sure if i'm fully utilizing the potential of fwrite. any help would be appreciated!

Well actually your statement will write the content of rec_arr to the standard output. However rec_arr contains pointers, and not true strings. The true strings are pointed by the elements of rec_arr, so what you print is those pointers. You can not use fwrite in such a way that it would dereference those pointers and print the string to the standard output or file. That is something you must do yourself, as you noted that for works correct. You could use puts() or fputs() if you think fprintf() would be too much.

Code:

int i;
for(i=0; i < rec_index; i++)
puts(rec_arr[i]);

I think thats the most efficient way to do this using C. Using fwrite() would be probably better if you knew the string lengths before hand. But still i think the performance hit is small.

A small note: fwrite doesn't care about the pointer type it gets. You need not cast it. And again, why cast a 'char *', which is the type of rec_arr[i] to a 'char **'? If you have the lengths stored, you should use them on the call to fwrite. Like:

It's better to just use puts when you're working with strings (unless they aren't NULL terminated).
And I suggest you avoid casting, as well. It can mask problems that you don't want.
Like sending a char** to puts will give you a warning, because that's not what you should use as argument.