ashu said:
look at code
#include<stdio.h>
int *mult(void);
int main(void)
{
int *ptr,i;
ptr=mult;
for(i=0;i<6;i++)
{
printf("%d",*(ptr++));
}
}
int *mult(void)
{
int ar[2][3]={1,2,3,4,5,6};
return = (int*) ar;
}
this program will not work, actually i am unable to reurn the address
of multi dimensional array
Please post the actual code that you compiled (cut-and-paste, don't
re-type). The code you posted contains a syntax error; the "return ="
should be just "return".
And don't just tell us it "will not work"; tell us *how* it doesn't
work. Does your program fail to compile? Do you get any diagnostics
from the compiler? Does the program crash at runtime? Do you get
unexpected output, and if so, what output did you expect?
Assuming that's the only difference between your actual code and the
code you posted, your compiler should have given you some warnings.
If it didn't, use whatever options your compiler requires to enable
more warnings, and pay attention to them.
You have
ptr=mult;
A function name not followed by parentheses evaluates the function
name and yields a function pointer; it *doesn't* call the function.
You want
ptr = mult();
(Perhaps that's what you had in your original program, but we can't
tell because you didn't post it.)
Inside your mult function, you declare a two-dimensional array "ar".
The initialization is ok, but it would be better to be more explicit:
int ar[2][3] = {{1,2,3}, {4,5,6}};
Note the additional whitespace; it makes the code much easier to read.
In the return statement (ignoring the "="), the expression ar (an
array name) is implicitly converted to a pointer to its first element;
in this case, it's a pointer to an array of 3 ints. You then use a
cast to convert this to a pointer-to-int.
Any cast should arouse suspicion. A cast, aside from specifying a
type conversion, tells the compiler "Don't bother me, I know what I'm
doing" -- but casts are too often used by programmers who *don't* know
what they're doing. Pointer casts are particularly problematic.
It looks like you're trying to treat a multidimensional 2-by-3 array
as if it were a one-dimensional array with 6 elements. This is
*probably* ok, but it's an odd thing to do. I can't tell from your
posted code why you can't just declare a one-dimensional array in the
first place.
Finally (and this is the most serious problem in your code, apart from
the syntax error), you attempt to return the address of a local
variable. As soon as the function returns, that local variable no
longer exists, and the caller has a dangling pointer value; any
attempt to deference that pointer value, or even examine it, invokes
undefined behavior. See questions 7.5a and 7.5b in the comp.lang.c
FAQ, <
http://www.c-faq.com/>.