7

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);
2
  • 1
    Please show your actual code - this example won't even compile. Commented Mar 1, 2012 at 6:02
  • 2
    You can't use strlen(out)! Read up what strlen does (or how C strings work, for that matter). You need to say x * y + x instead. And absolutely make sure that every array[i] is null-terminated. Commented Mar 1, 2012 at 6:32

2 Answers 2

12

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 );
Sign up to request clarification or add additional context in comments.

2 Comments

That works fine. Why doesn't this work: out = (char*)malloc(1000); strcat((*out), someString);
@RobertVbr, that probably doesnt work in your original func because you pass in uninitialized memory, strcat may never find a NUL terminator to start appending after.
0

It doesn't work because you never allocated memory for your result variable - it's just a pointer that points to nowhere.

char result[1000]; // change size as needed if you know the size ahead of time
func(result);

or

char *pResult = malloc ( 1000 ); // allocate dynamically

if ( pResult != NULL )
    func ( pResult );

...

if ( pResult != NULL )
    free ( pResult );

You should also pass in the size of your buffer so your func function can check and verify that there's enough space available for its output.

Both of these solutions assume that you allocate your buffer outside of func. If you want to allocate the output buffer inside func than - as suggested by Als - you need to pass a pointer-to-pointer. In that case, you should also return the size of the buffer so the caller knows how many bytes are available in the buffer.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.