Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning an array of char pointers

Tags:

c

pointers

I'm trying to return an array of char*'s to a function. I've simplified my code to a test case that clones a char array that instead of containing chars holds pointers to those chars.

/*
 * code.c
 */
#include <stdio.h>

char* makePointerCopy(char cIn[]);

int main() {
    char cTest[] = {'c', 't', 's', 't'};
    char* cPTest[] = makePointerCopy(cTest);
    printf("%p %c", cPTest, *cPTest);
    fflush(stdout);
    return 0;
}

char* makePointerCopy(char cIn[]) {
    char* cOut[sizeof(cIn)/sizeof(cIn[0])];
    int iCntr;

    for (iCntr = 0; iCntr < sizeof(cIn)/sizeof(cIn[0]); iCntr++)
        cOut[iCntr] = cIn + iCntr;

    return cOut;
}

A couple of warnings aside, this is what the compiler has to say about this code snippet:

invalid initializer (at char* cPTest[] = makePointerCopy(cTest);)

Why does this happen?

like image 895
Pieter Avatar asked Dec 02 '22 06:12

Pieter


1 Answers

Because makePointerCopy returns a char*, not a char*[].

You should be able to change that line to:

char* cPTest = makePointerCopy(cTest);

More specifically, the reason that you get THAT error message, rather than something about types, is that array initializers are required to be compile-time constants.

From http://bytes.com/topic/c/answers/215573-invalid-initializer

Even if the declaration is not at file scope, it would be illegal in both C90 and C99. C90 demands compile-time constant initializers for automatic and register arrays. And both C90 and C99 require a character array to be initialized with a) a string literal, or b) a brace-enclosed initializer list.

Still, the type mismatch is the actual problem here.

like image 140
danben Avatar answered Dec 10 '22 11:12

danben