By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
428,530 Members | 891 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 428,530 IT Pros & Developers. It's quick & easy.

How do I return this struct pointer?

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

Expand|Select|Wrap|Line Numbers
  1. level0.c: In function ‘create_grid’:
  2. level0.c:28:9: warning: return from incompatible pointer type [-Wincompatible-pointer-types]
  3.   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:

Expand|Select|Wrap|Line Numbers
  1. struct gridType* create_grid(int length){
  3.     char** array = malloc(length * sizeof(*array));
  4.     for(int i = 0; i < length; i++){
  5.         array[i] = malloc(length * sizeof(array));
  6.     }   
  8.     for(int i = 0; i < length; i++){
  9.         for (int j = 0; j < length; j++){
  10.             array[i][j] = '-';
  11.         }   
  12.     }   
  14.     struct gridType{
  15.         int length; 
  16.         char** array;
  17.     };
  19.     struct gridType* grid = malloc(sizeof(struct gridType));
  21.     grid->length = length;
  22.     grid->array = array;
  24.     return grid;
  25. }
Oct 22 '15 #1
Share this Question
Share on Google+
2 Replies

Expert Mod 5K+
P: 9,197
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
Expand|Select|Wrap|Line Numbers
  1. struct gridType{
  2.     int length;
  3.     char** array;
  4. };
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.
Oct 23 '15 #2

Expert 100+
P: 2,398
@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().
Expand|Select|Wrap|Line Numbers
  1. 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.
Oct 23 '15 #3

Post your reply

Sign in to post your reply or Sign up for a free account.