Typedef and complex declaration in C

Related to this issue.

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();

}
+3
source share
3 answers

Syntax:
Change
 typedef char (*p)[20] ptr;
For Image  typedef char (*ptr)[20];

To understand the syntax of typedef declarations like this. Imagine that you want to rename type T to type U. Declare a variable of type T named U and the declaration prefix with 'typedef'. All this.

semantically:
 See My and other answers to your related question. This behavior is undefined.

+8
source

You are returning a pointer to a memory that will no longer exist when myFunction () returns.

+4
source

, substr myFunction, myFunction , , .

-, typedef .

typedef char (*ptr)[20];

typedef , static extern ( ). ,

char (*ptr)[20]; // ptr is a pointer to a 20-element array of char

typedef :

typedef char (*ptr)[20];

- myFunction , , . :

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;
}
+2

Source: https://habr.com/ru/post/1772809/


All Articles