Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Populate C output parameter

Tags:

c

char

This is a beginner question, but please bear with me. I'd like to pass in a char* to a function, and have it populated, with the contents of multiple existing strings. Here's what I have (and doesn't work)

int func(char *out) {
    int i;
    int x = 10;
    int y = 10;
    char array[x][y];

    out = malloc(x * y + x);
    memset(out, 0x00, strlen(out));
    for (i=0; i<x; i++) {
            strcat(out, array[i]);
            strcat(out, "\n");
    }
}

//main
    char *result;
    func(result);
like image 712
Robert Vbr Avatar asked Mar 01 '12 05:03

Robert Vbr


1 Answers

A char* is just a pointer, passing it in doesnt let you pass a new one back out again. You need to pass a char** like so:

void get_name( char** ppname ){
  char * pname = strdup("my name is fred");
  *ppname = pname;
}

You then feed the function somewhere to put the pointer like so:

char * name;
get_name( &name );
printf( "got '%s'\n", name );
free( name );
like image 150
IanNorton Avatar answered Oct 06 '22 14:10

IanNorton