-4

How can one have a function returning a pointer to an array and what are the general things that one needs to keep in mind while doing that?

Kevin
  • 53,822
  • 15
  • 101
  • 132
chinmay
  • 850
  • 2
  • 8
  • 16

3 Answers3

2
 int (*foo(void))[4];

declares foo as a function with no parameters that returns a pointer to an array 4 of int.

For example:

int (*p)[4];
p = foo();
ouah
  • 142,963
  • 15
  • 272
  • 331
1

Typically a function would return a pointer to the zeroth element of an array.

int * f() {
  // ...

The trick is - who is responsible for the storage of the elements, the function or the caller?

maerics
  • 151,642
  • 46
  • 269
  • 291
-1
How can one have a function returning a pointer to an array

This function returns a pointer to an array :

  char * create_array() {
        char * array = malloc(ARRAY_SIZE, sizeof(char)); 
        return array; 
    }

However, if it is not strictly necessary you should avoid this practice. For example, the previous example is not a good c practice because it allocates memory in the heap, but delegates to another function the responsibility of freeing it.

Giuseppe Pes
  • 7,772
  • 3
  • 52
  • 90
  • 1
    `void` is not a pointer to an array, nor is `char *`. –  Aug 02 '13 at 21:06
  • 1
    And no, returning a pointer to `malloc()`ated memory is not bad practice at all. Conversely, it's quite common and idiomatic. –  Aug 02 '13 at 21:07
  • Yes, I know! I forgot to write the return type :D – Giuseppe Pes Aug 02 '13 at 21:07
  • However, it depends on what you are doing. I think the caller function should be responsible for allocating/de-allocating the memory and the called function should only modify the arrays values. This should reduce the risk of having area of memory that are not properly freed. – Giuseppe Pes Aug 02 '13 at 21:18
  • 1
    Counter example: the `malloc()` and `realloc()` routines allocate and reallocate memory that is subsequently freed by `free()` (or `realloc()` — the all-in-one memory management function). A little extreme, but not outrageously so. Less extreme examples include `strdup()` and `asprintf()` and its relatives. It is perfectly permissible and sensible to define a function that returns a pointer to allocated memory that becomes the responsibility of the called function to release. – Jonathan Leffler Aug 02 '13 at 21:28
  • I completely agree that sometimes is useful to let the callee function allocates the memory, and `strdup()` and `asprintf()` are good examples. However, I am thinking of a large context where several developers are working on the same code base, in this case, this practice may arise more then one problem because the knowledge of a developer cannot not be just limited to the interface exposed. To use correctly these functions, a developer should know how a function works internally and often they do not spend time doing so. I really appreciate your comments thanks! – Giuseppe Pes Aug 03 '13 at 07:26