Return Array in C?

前端 未结 4 712
春和景丽
春和景丽 2021-01-07 05:21

I cant return array in c,i am quite new to C so i probably do some kind of funny mistake, here is the code:

#define MAXSIZE 100
int recievedNumbers[MAXSI         


        
4条回答
  •  长发绾君心
    2021-01-07 05:36

    Try replacing int theArray[100] with int *theArray=malloc(100*sizeof int).

    While internally in C arrays are pointers arrays and pointers look very similar, they are of different type - this is what compiler is complaining about. Additionally, the compiler has saved you from a painful memory corruption error:

    when you define a local array variable inside your function, it gets memory allocated on function's stack. This gets released when function ends, so your result either becomes invalid or may become invalid later, or worse, cause various segmentation faults. malloc allocates memory in global application heap, it won't go bad after function terminates. But then, don't forget to free it after use.

提交回复
热议问题