Naman
Naman

Reputation: 1041

Compile time Error in C code [Returning an array pointer from function]

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<conio.h>

int main()
{
    int i, *ptr; 
    ptr = func();
    for(i=0;i<20;i++)
    {
        printf("%d", ptr[i]);
    }
    return 0;
}

int * func()
{
    int *pointer;
    pointer = (int*)malloc(sizeof(int)*20);
    int i;
    for(i=0;i<20;i++)
    {
        pointer[i] = i+1; 
    }
    return pointer;
}

ERROR: Conflicting type of func. Warning: Assignment makes Pointer from integer without a cast [enabled by default]

Why am I getting this error?

Upvotes: 3

Views: 244

Answers (1)

unwind
unwind

Reputation: 399753

Because you're calling func() without first declaring it. This causes the compiler to assume it's going to return int, but then you store that integer in a pointer which is of course rather suspicious.

Fix by moving func() to above main(), so the definition is seen before the call, or introduce a prototype before main():

int * func();

Also, functions taking no arguments should be (void) in C, and please don't cast the return value of malloc() in C.

Upvotes: 6

Related Questions