Thread: Help please!

  1. #1
    Trapped
    Guest

    Help please!

    hi,
    I need some help on the following issue.

    how should I declare a C function to return
    "char *temp[] "

    I tried to use char **, unfortunately it does not work.

    basically, I want to achieve this. suppose temp = {"abc", "de","2"}

    I want a function to be able to return a pointer so that I could
    achieve "abc", "de", "2" one by one.

    thanks

  2. #2
    S­énior Member
    Join Date
    Jan 2002
    Posts
    982
    You could do something like -

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    char** foo()
    {
    	char** arr= malloc(sizeof(char*)*3);
    	arr[0]="abc";
    	arr[1]="de";
    	arr[2]="2";
    	return arr;
    }
    
    int main(int argc, char* argv[])
    { 
    	char** arr = foo();
    	printf("%s %s %s",arr[0],arr[1],arr[2]);  
    	free(arr);
    	
        return 0;
    }
    However, you'd be better off allocating the memory before the function call and passing the pointer in as a parameter, so you don't forget that you need to free the memory. An alternative would be to create a struct of three char pointers, initialise each pointer to a literal in the function, and return the struct. This would remove the need for memory management.

    Also it probably wont work if you need to modify the strings.

Popular pages Recent additions subscribe to a feed