Related to this question.
What is wrong with the following code?
typedef char (*p)[20] ptr;
ptr myFunction () {
char sub_str[10][20];
return sub_str;开发者_运维百科
}
int main () {
ptr str;
str = myFunction();
}
Syntactically:
Change
typedef char (*p)[20] ptr;
To
typedef char (*ptr)[20];
To understand the syntax of typedef-declarations like this. Imagine you want to rename type T to type U. Declare a variable of type T named U and prefix the declaration with 'typedef'. That's all.
Semantically:
See my and other answers to your linked question. This is still undefined behavior
You're returning a pointer to memory that will not exist anymore when myFunction() returns.
The main problem is that substr
is local to myFunction
, and once myFunction
exits it no longer exists, so the pointer you return will no longer be valid.
Secondly, you are not using typedef
correctly. The proper syntax would be
typedef char (*ptr)[20];
Syntactically,typedef
basically acts like a storage class specifier similar to static
or extern
(although the semantics are different). Basically, you figure out the declaration for an object
char (*ptr)[20]; // ptr is a pointer to a 20-element array of char
and then add the typedef
to it:
typedef char (*ptr)[20];
Somehow myFunction
needs to allocate memory in such a way that it isn't destroyed as soon as the function exits. Here's one option:
typedef char (*ptr)[20];
ptr myFunction(size_t count)
{
/**
* Dynamically allocate a block of N 20-element arrays of char
*/
ptr p = malloc(sizeof *ptr * count);
return p;
}
int main(void)
{
ptr str = myFunction(10);
size_t i, j;
for (i = 0; i < 10; i++)
for (j = 0; j < 20; j++)
str[i][j] = ...;
...
free(str);
return 0;
}
精彩评论