How do I return this struct pointer?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • pinnockf
    New Member
    • Oct 2015
    • 1

    How do I return this struct pointer?

    I am having trouble understanding why the compiler is giving me the following error:

    Code:
    level0.c: In function ‘create_grid’:
    level0.c:28:9: warning: return from incompatible pointer type [-Wincompatible-pointer-types]
      return grid;
    I am simply trying to return a pointer to a struct that I created in the function.

    The code for the function is:

    Code:
    struct gridType* create_grid(int length){
        
        char** array = malloc(length * sizeof(*array));
        for(int i = 0; i < length; i++){
            array[i] = malloc(length * sizeof(array));
        }   
        
        for(int i = 0; i < length; i++){
            for (int j = 0; j < length; j++){
                array[i][j] = '-';
            }   
        }   
            
        struct gridType{
            int length; 
            char** array;
        };
    
        struct gridType* grid = malloc(sizeof(struct gridType));
    
        grid->length = length;
        grid->array = array;
    
        return grid;
    }
    Last edited by pinnockf; Oct 22 '15, 10:28 PM. Reason: typo
  • weaknessforcats
    Recognized Expert Expert
    • Mar 2007
    • 9214

    #2
    C is sloppy. It makes assumptions when it shouldn't. One of these occurs when you use a pointer to a type before you define it.

    Your solution here is to move all
    Code:
    struct gridType{
    	int length;
    	char** array;
    };
    from inside your functions to the top of the file and outside any function. That way gridType is clearly declared and no assumptions will be made by the compiler.

    Comment

    • donbock
      Recognized Expert Top Contributor
      • Mar 2008
      • 2427

      #3
      @weaknessforcat 's advice should get rid of the error message.

      You should verify that malloc didn't fail before dereferencing the pointer it returns.
      You should also decide what your function will return when malloc fails (NULL is a good choice).

      By the way, if it should turn out that users of create_grid() don't ever directly access the structure fields then you have the option of providing an "incomplete definition" of the structure to users of create_grid().
      Code:
      struct gridType;
      This is enough to declare pointers to grid_type. You only need the complete structure definition where you access structure fields or allocate memory to hold the structure.

      Comment

      Working...