Slash
Slash

Reputation: 91

(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.

Upvotes: 0

Views: 1615

Answers (3)

0___________
0___________

Reputation: 67546

  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)); 
     /* ... */

Upvotes: 2

TImothy K. Worrell
TImothy K. Worrell

Reputation: 1

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.

Upvotes: -1

SamHuffman
SamHuffman

Reputation: 567

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:

Upvotes: 0

Related Questions