-1

I have a function like char ** f(). It returns the address of a variable char* a[].I stored this return type in variable char ** s, but I want to print all the values of char * a[]. How is this possible?

Thanx.

SplinterReality
  • 3,400
  • 1
  • 23
  • 45
A_Gupta
  • 87
  • 9
  • is this a serious question? – Nowayz Feb 19 '14 at 05:38
  • 1
    You need to know what size of `char **`. – herohuyongtao Feb 19 '14 at 05:40
  • 1
    Either you need to know the size of the array (have a separate function that returns that, or return a struct containing both the array and the length), or you have to know that there will be some mark (like the null termination in a string) as the last element of the array and scan for that to find the length, or you need to do something like encoding the length into the array's first entry... Once you know the length, the rest should be obvious. – keshlam Feb 19 '14 at 05:44
  • This question is a troll I think. Otherwise please post your code because it's impossible to tell what you actually want. You shouldn't generally be returning char* pointers unless you are mallocing them for some reason in the function in which case you should know their size, and you should just use printf to print. – Nowayz Feb 19 '14 at 05:44
  • @herohuyongtao:no,i want values – A_Gupta Feb 19 '14 at 12:03
  • possible duplicate of [How to reliably get size of C-style array?](http://stackoverflow.com/questions/2404567/how-to-reliably-get-size-of-c-style-array) – Seki Feb 19 '14 at 22:09

2 Answers2

1

Just remember that you're dealing with an array of pointers.

Assuming (and this is a generally unsafe assumption) that your list of pointers ends with a null, in much the same way a string ends with a null, you can use a simple for loop to access the char* in the array similar to the following:

for (int index = 0; index++ ; a[index] != null) {
    char * myString = a[index];
    printf("Value: %s\n",myString);
}

The other posters are right, you need to know how many char *s you're dealing with, and so far that information isn't apparent. The above answer makes a HUGE assumption about the structure of the data you're dealing with, and WILL segfault your application if that assumption is incorrect.

Ferenc Deak
  • 34,348
  • 17
  • 99
  • 167
SplinterReality
  • 3,400
  • 1
  • 23
  • 45
0

sample

#include <stdio.h>
#include <stdlib.h>

char **f(void){
    char **array = malloc(sizeof(char*)*6);
    array[0] = "fox";
    array[1] = "jumps";
    array[2] = "over";
    array[3] = "lazy";
    array[4] = "dog";
    array[5] = NULL;
    return array;
}

int main() {
    char ** s = f();
    for(int i=0;s[i];++i)
        printf("%s\n", s[i]);
    free(s);
    return 0;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70