473,786 Members | 2,737 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

program that return an address of multi dimensional array

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",*(p tr++));
}
}

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

Feb 12 '06 #1
7 5827
In article <11************ **********@f14g 2000cwb.googleg roups.com>,
ashu <ri*********@ya hoo.com> wrote:
look at code
#include<stdio .h>
int *mult(void);
That declares that mult is a function taking no arguments and
returning a pointer to an int .
int main(void)
{
int *ptr,i;
That declares that ptr is a pointer to an int .
ptr=mult;
That tries to set ptr (a pointer to an int) to the address of
the mult() function itself (i.e., a pointer to a function that
returns a pointer to an int). This is a type conflict and your
compiler probably complained about this.
for(i=0;i<6;i++ )
{
printf("%d",*(p tr++));
}
}

int *mult(void)
{
int ar[2][3]={1,2,3,4,5,6};
This declares an automatic variable named ar as a 2D array of int,
and initializes it to some values.
return = (int*) ar;
This takes the address of ar (a 2D array of int), reinterprets the
type as being a pointer to int, and returns that value.
}
this program will not work, actually i am unable to reurn the address
of multi dimensional array


You aren't calling mult, you are only referring to it. And if you
did call it, you would be trying to return from it the address
of an automatic variable -- an address that would go out of scope
and so be invalid as soon as the mult() function returned. Never
return the address of an automatic variable -- at least not
in any context where you intended to try to access storage there.

--
"It is important to remember that when it comes to law, computers
never make copies, only human beings make copies. Computers are given
commands, not permission. Only people can be given permission."
-- Brad Templeton
Feb 12 '06 #2
On Sat, 11 Feb 2006 20:27:51 -0800, ashu wrote:
look at code
OK
return = (int*) ar;


return = ??

This is a small point, include it when considering the other useful advice
I see has been posted already.

--
Ben.

Feb 12 '06 #3
"ashu" <ri*********@ya hoo.com> writes:
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",*(p tr++));
}
}

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 multidimensiona l 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/>.

--
Keith Thompson (The_Other_Keit h) ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
Feb 12 '06 #4
ashu wrote:

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",*(p tr++));
}
}

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


It's actually undefined to step through two consective arrays
with any kind of pointer except a pointer to a char type,
even though attempting to do that, works on my machine.

/* BEGIN new.c */

#include<stdio. h>

int *mult(void);

int main(void)
{
int *ptr, i;

ptr = mult();
for (i = 0; i < 6; i++) {
printf("%d", *(ptr++));
}
putchar('\n');
return 0;
}

int *mult(void)
{
static int ar[] = {1, 2, 3, 4, 5, 6};

return ar;
}

/* END new.c */
--
pete
Feb 12 '06 #5
ashu wrote:
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",*(p tr++));
}
}

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


There are enough things wrong with your small program to suggest that
you need to start reading your C-book from the beginning. Pay attention
this time.
I'm not at all happy with return the address of an int[2][3] as a int *,
but check the following:

#include <stdio.h>
int *mult(void);
int main(void)
{
int *ptr, i;
ptr = mult(); /* mha: note '()' */
for (i = 0; i < 6; i++) {
printf("%d", *(ptr++));
}
putchar('\n'); /* mha: note EOL char at EOL */
return 0; /* mha: returning a value from a
function promising to return a value
*/
}

int *mult(void)
{
static int ar[2][3] = { {1, 2, 3}, {4, 5, 6} };
/* mha: note 'static' */

return (int *) ar; /* mha: note no '=' */
}

Feb 12 '06 #6
On 11 Feb 2006 20:27:51 -0800, "ashu" <ri*********@ya hoo.com> wrote:

snip non-working code
this program will not work, actually i am unable to reurn the address
of multi dimensional array


To return the address of a multi-dimensional array, you need:

1 - A function with the correct return type.
2 - A return statement that returns the correct type
3 - Some insurance that the array will remain in existence
after the function returns

It is probably desirable to have:

4 - A variable in the calling function to receive the type

If you typedef array_t to the type of array whose address you want to
return, as in the example
typedef int array_t[5][7][93];
then you can use
array_t* function(...); /* function prototype */
and
array_t* function(...){
static array_t x; /* array exists forever */
...
return &x;
} /* function definition */
and
array_t *ptr;
...
ptr = function(...); /* in calling function */

Since you specified returning the address of the array, return x in
function would not be appropriate since it returns a pointer to the
first element of the array (which has the same address but the wrong
type).

If you don't use the typedef, you can get some pretty ugly
declarations such as
int (*)[5][7][93] function(...); /* prototype */
Remove del for email
Feb 13 '06 #7
In article <2i************ *************** *****@4ax.com>
Barry Schwarz <sc******@doezl .net> wrote:
To return the address of a multi-dimensional array ... [snip a bunch of correct stuff]
If you don't use the typedef, you can get some pretty ugly
declarations such as
int (*)[5][7][93] function(...); /* prototype */


Minor but significant syntactic correction here: you mean:

int (*function(args ))[5][7][93];

(I prefer to wrap complicated array-of-array types in structures
when dealing with code like this. Using "struct" not only gives
you a user-defined abstract type -- the keyword does stand for
STRange spelling for User-defined abstraCt Type, after all :-) --
it also avoids the need for a typedef-alias.)
--
In-Real-Life: Chris Torek, Wind River Systems
Salt Lake City, UT, USA (40°39.22'N, 111°50.29'W) +1 801 277 2603
email: forget about it http://web.torek.net/torek/index.html
Reading email is like searching for food in the garbage, thanks to spammers.
Feb 20 '06 #8

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

2
7673
by: ip4ram | last post by:
I used to work with C and have a set of libraries which allocate multi-dimensional arrays(2 and 3) with single malloc call. data_type **myarray = (data_type**)malloc(widht*height*sizeof(data_type)+ height* sizeof(data_type*)); //allocate individual addresses for row pointers. Now that I am moving to C++,am looking for something by which I can
5
2556
by: Cant Think Today | last post by:
I have multi-dimesional arrays that can be specifed by the user, e.g 1,2,3,4,5 1,2,3,4,5,6,7,8,9,10 1,2,3,4,5,6 I think a bit of code that will iterate over these arrays to print out the element indices for each unique element in the N-dimensional array. E.g. for the above
5
2938
by: Andrew Poulos | last post by:
If I'm searching for an occurance of a value in a multi-dimensional array how can I get it's index returned as an array, if found? For example, if: foo = new Array(); foo = , 5, , 9, 10]; Array.prototype.findValue = function(val) { // blah }
1
593
by: Matthew Jakeman | last post by:
How can i create a multi dimensional array of "strings"? I've tried char * ; no joy Cheers for any help Matt
4
4519
by: Robert P. | last post by:
I can easily store a one-dimensional array in viewstate ( see Test1 ) If I try storing a multi-dimensional array in the viewstate it's crapping out on me when it goes to serialize the array (not when I make the assignment). Interestingly, I get a very different error depending on the type of array ( string or decimal ). I'm not doing anything fancy, just a regular old aspx page with a single
4
3037
by: Balaskas Evaggelos | last post by:
Hi, does anyone know how i can sort a multi-dimensional array by a specific field ? for example i want to sort arr where n=2, but i need the data of every array to follow that order. example array: arr
4
1648
by: nembo kid | last post by:
I have the following bidimensional array int a ; Why the first address of this array is only: & (mat) and not also:
152
9916
by: vippstar | last post by:
The subject might be misleading. Regardless, is this code valid: #include <stdio.h> void f(double *p, size_t size) { while(size--) printf("%f\n", *p++); } int main(void) { double array = { { 3.14 }, { 42.6 } }; f((double *)array, sizeof array / sizeof **array); return 0;
4
7329
by: =?Utf-8?B?SGVucmlrIFNjaG1pZA==?= | last post by:
Hi, consider the attached code. Serializing the multi-dimensional array takes about 36s vs. 0.36s for the single-dimensional array. Initializing the multi-dimensional array takes about 4s vs. 0.3s for the single-dimensional array. (I know initializing is not necessary in this simple example,
0
9647
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10363
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
10164
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10110
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8989
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7512
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6745
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5534
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4066
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.