- #include<stdio.h>
-
main()
-
{
-
int a[] = {345,342,784,1223,1,775,3,1,234};
-
int b[] = {};
-
int x,*y,m;
-
x = sizeof(a)/sizeof(a[0]);
-
y = malloc((int *)sizeof(a));
-
m = int * arrayreturn(*b);
-
printf("%d\n",x);
-
printf("%d\n",y);
-
printf("%d\n",m);
-
printf("%d",y[0]);
-
getch();
-
}
-
-
int arrayreturn(int *b)
-
{
-
int x = 3;
-
return x;
-
}
can anybody tell me whats the error in above program?
There are quite a lot, actually:
1) You are using main(), which is not advisable. Instead, write int main(), and at the very end, write return 0; This is the standard practice.
2) Using the sizeof() tricks to find the size of the array works here...but only here. Don't rely on that trick to get the size of an array in functions...in fact, it's better to get used to hardcoding a size for your array (i.e. a global constant variable SIZE).
3) Your malloc call is incorrect. malloc returns a void*, and your code expects an int*. I suppose that's why you included the typecast, but the place you put it is completely incorrect. That takes the size of a and casts it to a pointer, then tries to make that many bytes of memory - not going to work.
4) Just because you get memory for y (assuming you fix the malloc call) doesn't mean it has meaningful values, so printing out y[0] won't give you any useful information.
5) Your function call is incorrect - in the call, you don't include the return type. If you do, C will think you are declaring a new function and probably complain.
6) Your argument to arrayreturn is incorrect - you pass it *b (which is an int, since b is an int*), but the function expects an int*. You should be passing b.
7) Your function doesn't actually use the argument, so what's the point?
This function has a lot of flat out wrong code - are you diving too deep into programming? You may want to study the syntax of these simple manipulations before trying any pointer manipulation or function calls.