简体   繁体   中英

Return array from function -conflicting types for

My purpose is to create an array in a function and then return it to the main function. I was recommended to allocate the array on the heap in the function (otherwise popped from the stack as soon as its returned).

The code is shown below:

 #include <stdlib.h>
 int main() {

    double *v1 = myFunction();

    return 0;
 }



 double *myFunction() {
   return malloc(10*sizeof(double));
 }

When I compile this code with gcc I get the following error-message:

 ..\src\main3.c:38:9: error: conflicting types for 'myFunction'

What is wrong with this code? Why do I get this compilation error?

Provide myFunction() 's prototype before using it, that is before main() like so:

double * myFunction();

int main(void)
{
  ...

If not doing so, the compiler assumes type int for myFunction() when seeing it for the first time.

Than later it finds it to be declared as double * (being different from int ) which then provokes the error.

Turning on all warnings would have pointed you to using a function without prototype. Use -Wall -Wextra -pedantic to turn on most of gcc's warnings.


Another issue is that declaring a function without any arguments specified leaves it open what to pass on calling the function:

double * myFunction();

If a function should be specfied to not have any arguments specify void as argument:

double * myFunction(void);

The same for how your code defines main() . It shall be:

int main(void);

or either be

int main(int argc, char ** argv);

1) Add prototype of myfunction at the starting like following or

double *myFunction();
 int main() {
    double *v1 = myFunction();
    return 0;
 }
 double *myFunction() {
   return malloc(10*sizeof(double));
 }

2). or define the functionBody before it is called

 double *myFunction() {
   return malloc(10*sizeof(double));
 }

 int main() {
    double *v1 = myFunction();
    return 0;
 }

However, first solution is preferable.

Your code is almost fine, there's only one little but blocking error, you are trying to use myFunction before the symbol is defined, all you have to do is :

#include <stdlib.h>
double *myFunction() { // myFunction should be declared before it's used
    return malloc(10*sizeof(double));
}

int main() {
    double *v1 = myFunction();
    return 0;
}

The the open C book states "All identifiers in C need to be declared before they are used. This is true for functions as well as variables." the beauty in C is that you can do can do amazing stuff like this piece of code , but you should follow some guidelines, read the open C book!.

Cheers.

尝试这个..

 return (double*) malloc(10*sizeof(double));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM