(Returning char (*)(255) from a function with incompatible return type 'char **') error in C

I have this code:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <ctype.h>

static char** testing(FILE *fp)
{ 
    char temp[255];
    char data[255][255]; 
    for (int i = 0; !feof(fp); i++)
    {
        fgets(temp, 255, fp);
        strcpy(data[i], temp);
    }
    
    for (int i = 0; i < 66; i++)
    {
        printf("%s", data[i]);
    }

    return data;
}

int main(int argc, char const *argv[])
{
    FILE *fp; 

    fp = fopen(argv[1], "r");
    testing(fp);
}

I want to return the 2D array data but when I compile this, I get the output:

returning 'char (*)[255]' from a function with incompatible return type 'char **' [-Wincompatible-pointer-types] return data;

I don't see what I've done wrong.

Any help would be very much appreciated.

3 answers

  • answered 2021-05-14 20:41 SamHuffman

    Your data variable is not allocated dynamically and therefor cannot be used outside your function. You need to return a pointer to a dynamically allocated array to use it outside of it.

    Here for more details about heap and stack:

  • answered 2021-05-14 22:05 TImothy K. Worrell

    You declared the return value to be a char** which can be interpreted by reading from right to left, so is a pointer to a pointer of type char. While data is a two dimensional array. Returning data as you do, is returning the pointer to data, which the compiler sees as a pointer to a one-dimensional array. That is why you got an incompatible data error. Additionally you have issue with using a locally declared variable which is not visible outside the function so the value returned would result in a protection fault.

  • answered 2021-05-14 22:17 0___________

    1. data is two-dimensional array of chars. When 2D array decals to a pointer it has the type of pointer to the char array.

    the function should be declared as :

    static char (*testing(FILE *fp))[255]
    
    1. Returning the pointer to local object is dangerous as dereferencing the returned pointer invokes Undefined Behaviour. The local automatic variables stop existing when a function returns. You need to use (a)global variables, (b)static variables or use (c)malloc family functions to allocate the memory.

    (a):

    char data[255][255]; 
    static char (*testing(FILE *fp))[255]
    {
         /* ... */
    

    (b):

    static char (*testing(FILE *fp))[255]
    {
        static char data[255][255]; 
         /* ... */
    

    (c):

    static char (*testing(FILE *fp))[255]
    {
        char (*data)[255] = malloc(255 * sizeof(*data)); 
         /* ... */