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?
char* cOut[sizeof(cIn)/sizeof(cIn[0])];will not work. A simplechar cIn[]in the argument list will not have the size information of the array included. You need something liketemplate<size_t N> ... (char (&cIn)[N]), then N will match the number of elements. Alternative: usechar* start, char* endto pass the array.makePointerCopycall do the trick too, provided that I pass on iSize to the function?int iSize = sizeof(cTest)/sizeof(cTest[0]);