473,386 Members | 1,962 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

Array Initialization

I finally thought I had an understanding of multi dimensional arrays in C
when I get this:

#include <stdio.h>

#define max_x 3
#define max_y 5

int array[max_x][max_y];

main()
{
int x,y;

for(x = 0; x < max_x; x++)
for(y=0; y < max_y; y++)
array[x][y] = x * 10 + y;

for(y = 0; y < max_y; y++) {
(void)printf("array[%d] ", y);
for(x = 0; x < max_x; x++)
(void)printf("%d ", array[x,y]);
(void)printf("\n");
}

return 0;
}

This program initializes to :
array[0] 56164 56164 56164
array[1] 56184 56184 56184
array[2] 56204 56204 56204
array[3] 56224 56224 56224
array[4] 56244 56244 56244

Could someone please help me figure out how this program arrives at such a
large number?
Nov 13 '05 #1
19 4518
>Subject: Array Initialization
From: "Henry" he*****@knology.net
Date: 9/2/03 3:27 PM Hawaiian Standard Time
Message-id: <vl************@corp.supernews.com>

I finally thought I had an understanding of multi dimensional arrays in C
when I get this:

#include <stdio.h>

#define max_x 3
#define max_y 5

int array[max_x][max_y];

main()
{
int x,y;

for(x = 0; x < max_x; x++)
for(y=0; y < max_y; y++)
array[x][y] = x * 10 + y;

for(y = 0; y < max_y; y++) {
(void)printf("array[%d] ", y);
for(x = 0; x < max_x; x++)
(void)printf("%d ", array[x,y]);
(void)printf("\n");
}

return 0;
}

This program initializes to :
array[0] 56164 56164 56164
array[1] 56184 56184 56184
array[2] 56204 56204 56204
array[3] 56224 56224 56224
array[4] 56244 56244 56244

Could someone please help me figure out how this program arrives at such a
large number?


Heck, I'm interested to know how this even compiled.

(void)printf("%d ", array[x,y]);

Should be .. array[x][y]....

Fortran dies hard, don't it? :-)

Stuart
Dr. Stuart A. Weinstein
Ewa Beach Institute of Tectonics
"To err is human, but to really foul things up
requires a creationist"
Nov 13 '05 #2
On Tue, 2 Sep 2003 21:27:36 -0400, "Henry" <he*****@knology.net>
wrote:
I finally thought I had an understanding of multi dimensional arrays in C
when I get this:

#include <stdio.h>

#define max_x 3
#define max_y 5

int array[max_x][max_y];

main()
{
int x,y;

for(x = 0; x < max_x; x++)
for(y=0; y < max_y; y++)
array[x][y] = x * 10 + y;

for(y = 0; y < max_y; y++) {
(void)printf("array[%d] ", y);
for(x = 0; x < max_x; x++)
(void)printf("%d ", array[x,y]);
(void)printf("%d ", array[x][y]);

array[x,y] uses the comma operator and is the same as array[y].

You're invoking UB because array[y] has type 'int *' and
you're printing it with %d.
(void)printf("\n");
}

return 0;
}

This program initializes to :
array[0] 56164 56164 56164
array[1] 56184 56184 56184
array[2] 56204 56204 56204
array[3] 56224 56224 56224
array[4] 56244 56244 56244

Could someone please help me figure out how this program arrives at such a
large number?


Nick.
Nov 13 '05 #3
In article <vl************@corp.supernews.com>,
Henry <he*****@knology.net> wrote:
I finally thought I had an understanding of multi dimensional arrays in C
when I get this:

int array[max_x][max_y];

(void)printf("%d ", array[x,y]);


array[x,y] is not the same thing as array[x][y].
The expression:
x,y
is a comma expression whose value is the value of the second
expression (in this case, y). The first expression (in this case, x)
would be evaluated for its side effects; but in this case, there are
none. So x,y is equivalent to just:
y

So you effectively have
printf("%d ", array[y])

array[y] is type (pointer to int). "%d" requires an int. So you're
using an "int" format specifier to print a (pointer to int); the result
is undefined. Change the code to:
printf("%d ", array[x][y]);
and you'll probably get what you expected.

By the way, I'm curious what platform you are running on. (i.e. what
compiler and what OS and what processor)? I'm somewhat surprised at
the numbers you got. (It's all undefined, of course ... but on a
typical PC platform, I'd have expected the actual result to be much
larger than the numbers you got.)

-- Brett
Nov 13 '05 #4
In article <20***************************@mb-m23.aol.com>,
Bigdakine <bi*******@aol.comGetaGrip> wrote:

Heck, I'm interested to know how this even compiled.
(void)printf("%d ", array[x,y]);


Why wouldn't it? 'x,y' is a perfectly valid expression (equivalent to
'y'), and array[y] doesn't violate any constraints (and would even be
useful, defined behavior under some circumstances), so one wouldn't
expect compilation to fail. Of course, array[y] is type (pointer to
int), so attempting to print it with "%d" is undefined behavior.

-- Brett
Nov 13 '05 #5
> is a comma expression whose value is the value of the second
expression (in this case, y). The first expression (in this case, x)
would be evaluated for its side effects; but in this case, there are
none. So x,y is equivalent to just:
y

So you effectively have
printf("%d ", array[y])


Ok thanks, when I changed the way it was typed it worked much better..
Strangly the array[x,y] came straight from the "Practical C" book.

The new initialization is this:
array[0] 0 10 20
array[1] 1 11 21
array[2] 2 12 22
array[3] 3 13 23
array[4] 4 14 24

This seems like a much more plausible answer.. Although I am still a little
confused as to how it arrives at the numbers in that order. Could someone
explain it to me a little clearer? The book is not doing a very good job.

Thanks
Nov 13 '05 #6
Henry wrote:
I finally thought I had an understanding of multi dimensional arrays in C
when I get this:

#include <stdio.h>

#define max_x 3
#define max_y 5

int array[max_x][max_y];

main()
For goodness' sake! Why would anyone use an implicit int as the return
value for main, and then decorate printf calls with casts?
[...]
(void)printf("array[%d] ", y);


If you do this to satisfy some version of lint, get one that knows that not
only is an explicit 'int' on main a good idea, but it is required by the
current C standard.

--
Martin Ambuhl

Nov 13 '05 #7
"Henry" <he*****@knology.net> wrote in
<vl************@corp.supernews.com>:
I finally thought I had an understanding of multi dimensional arrays in C
when I get this:

#include <stdio.h>

#define max_x 3
#define max_y 5

int array[max_x][max_y];

main() int main(void){
int x,y;

for(x = 0; x < max_x; x++)
for(y=0; y < max_y; y++)
array[x][y] = x * 10 + y;

for(y = 0; y < max_y; y++) {
(void)printf("array[%d] ", y); Get rid of these (void) casts - you don't need them.
for(x = 0; x < max_x; x++)
(void)printf("%d ", array[x,y]); ^^^^^
Shouldn't this read: array[x][y] ???
(void)printf("\n");
}

return 0;
}

This program initializes to :
array[0] 56164 56164 56164
array[1] 56184 56184 56184
array[2] 56204 56204 56204
array[3] 56224 56224 56224
array[4] 56244 56244 56244
Not at all - the initialization is just perfect.
Could someone please help me figure out how this program arrives at such a
large number?

You print array[x,y], which is equivalent to array[y], which is
in turn a pointer to an array of five ints, which you print using
the %d format specifier - hence the 'strange' values.

Irrwahn
--
Rain is just liquid sunshine.
Nov 13 '05 #8
In article <vl************@corp.supernews.com>, Henry wrote:
I finally thought I had an understanding of multi dimensional arrays in C
when I get this:

#include <stdio.h>

#define max_x 3
#define max_y 5

int array[max_x][max_y];

main()
{
int x,y;

for(x = 0; x < max_x; x++)
for(y=0; y < max_y; y++)
array[x][y] = x * 10 + y;

for(y = 0; y < max_y; y++) {
(void)printf("array[%d] ", y);
for(x = 0; x < max_x; x++)
(void)printf("%d ", array[x,y]);
(void)printf("\n");
}

return 0;
}

This program initializes to :
array[0] 56164 56164 56164
array[1] 56184 56184 56184
array[2] 56204 56204 56204
array[3] 56224 56224 56224
array[4] 56244 56244 56244

Could someone please help me figure out how this program arrives at such a
large number?


The statement

(void)printf("%d ", array[x,y]);

prints the value of array[y] because the value of expression x,y is y.
You likely meant to write

(void)printf("%d ", array[x][y]);

Because the array is a two dimensional array, the value of array[y] is a
pointer to a one-dimensional array. The values being printing in each
row are &array[0][0], &array[1][0], &array[2][0], &array[3][0], and
&array[4][0].
Nov 13 '05 #9
Irrwahn Grausewitz <ir*****@freenet.de> wrote in
<uh********************************@4ax.com>:

Arrrrrrrrrrrgh, I did it again, stupid me!
<snip>
in turn a pointer to an array of five ints, which you print using

^^^^^^^^^^^^^^^^
<delete this>
<snap>

--
Rain is just liquid sunshine.
Nov 13 '05 #10
"Henry" <he*****@knology.net> wrote in
<vl************@corp.supernews.com>:
<SNIP>
Ok thanks, when I changed the way it was typed it worked much better..
Strangly the array[x,y] came straight from the "Practical C" book. If there are more flaws like this in the book, get a better one.
(Btw.: were the (void) casts for printf straight from that book, too?
The new initialization is this:
array[0] 0 10 20
array[1] 1 11 21
array[2] 2 12 22
array[3] 3 13 23
array[4] 4 14 24

This seems like a much more plausible answer.. Although I am still a little
confused as to how it arrives at the numbers in that order. Could someone
explain it to me a little clearer? The book is not doing a very good job.

You initialize the array like that:

for(x = 0; x < max_x; x++)
for(y = 0; y < max_y; y++)
array[x][y] = x * 10 + y;

and print it out this way:

for(y = 0; y < max_y; y++)
{
printf("array[%d] ", y);
for(x = 0; x < max_x; x++)
printf("%d ", array[x,y]);
printf("\n");
}

and this is what you get:
x
0 1 2
y +---------
0| 0 10 20
1| 1 11 21
2| 2 12 22
3| 3 13 23
4| 4 14 24

Your confusion may rise from the fact that you arranged the loops
in different ways for the initialization and the output, but that
changes absolutely nothing - well, as long as you use x and y in
a consistent manner, which you perfectly did.

--
Rain is just liquid sunshine.
Nov 13 '05 #11

"Brett Frankenberger" <rb*@panix.com> wrote in message
news:bj**********@reader2.panix.com...
In article <20***************************@mb-m23.aol.com>,
Bigdakine <bi*******@aol.comGetaGrip> wrote:

Heck, I'm interested to know how this even compiled.
(void)printf("%d ", array[x,y]);


Why wouldn't it? 'x,y' is a perfectly valid expression (equivalent to
'y'), and array[y] doesn't violate any constraints (and would even be
useful, defined behavior under some circumstances), so one wouldn't
expect compilation to fail. Of course, array[y] is type (pointer to
int), so attempting to print it with "%d" is undefined behavior.

-- Brett


Yes, it can be compiled. The comma between a and b is "comma operator".
The expression "a,b" will return "b" silently. You can even write

array[ printf("Hello man") , y]
To OP :
It dosen't mean "array[x,y] " is the correct syntax for accessing
two-dimensional
array. You should write "array[x][y]".

--
Jeff


Nov 13 '05 #12

"Henry" <he*****@knology.net> wrote in message
news:vl************@corp.supernews.com...
is a comma expression whose value is the value of the second
expression (in this case, y). The first expression (in this case, x)
would be evaluated for its side effects; but in this case, there are
none. So x,y is equivalent to just:
y

So you effectively have
printf("%d ", array[y])


Ok thanks, when I changed the way it was typed it worked much better..
Strangly the array[x,y] came straight from the "Practical C" book.


Burn your book :-)

[snip]

--
Jeff
Nov 13 '05 #13
> > Ok thanks, when I changed the way it was typed it worked much better..
Strangly the array[x,y] came straight from the "Practical C" book.


Burn your book :-)

[snip]

--
Jeff


LOL

Well I started learning C using the K&R book but it assumed too much, so I
was told "Practical C" would be a much better book to go through because it
would be more in depth and would cover topics that K&R would seemingly skip
over. So far "PC" has been compeltly different.. using commands such as
scanf and fgets which K&R didn't even mention
Nov 13 '05 #14

"Irrwahn Grausewitz" <ir*****@freenet.de> wrote in message
news:62********************************@4ax.com...
"Henry" <he*****@knology.net> wrote in
<vl************@corp.supernews.com>:
<SNIP>
Ok thanks, when I changed the way it was typed it worked much better..
Strangly the array[x,y] came straight from the "Practical C" book.

If there are more flaws like this in the book, get a better one.
(Btw.: were the (void) casts for printf straight from that book, too?


Yes... it seemed strange to me that they would expect a return on printf
Nov 13 '05 #15
Jeff <no*****@notexist.com> scribbled the following:
"Brett Frankenberger" <rb*@panix.com> wrote in message
news:bj**********@reader2.panix.com...
In article <20***************************@mb-m23.aol.com>,
Bigdakine <bi*******@aol.comGetaGrip> wrote:
>
>Heck, I'm interested to know how this even compiled.
> (void)printf("%d ", array[x,y]);
Why wouldn't it? 'x,y' is a perfectly valid expression (equivalent to
'y'), and array[y] doesn't violate any constraints (and would even be
useful, defined behavior under some circumstances), so one wouldn't
expect compilation to fail. Of course, array[y] is type (pointer to
int), so attempting to print it with "%d" is undefined behavior.

Yes, it can be compiled. The comma between a and b is "comma operator".
The expression "a,b" will return "b" silently. You can even write array[ printf("Hello man") , y] To OP :
It dosen't mean "array[x,y] " is the correct syntax for accessing
two-dimensional
array. You should write "array[x][y]".


However, due to C's wacky ways of working, the following code is
perfectly legal:

#include <stdio.h>
int main(void) {
int array[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 };
printf("%d\n", array[printf("Hello man\n")]);
return 0;
}

This should print out:
Hello man
11

Because "Hello man\n" is 10 printable characters (and a '\0'), and
array[10] is 11.

--
/-- Joona Palaste (pa*****@cc.helsinki.fi) ---------------------------\
| Kingpriest of "The Flying Lemon Tree" G++ FR FW+ M- #108 D+ ADA N+++|
| http://www.helsinki.fi/~palaste W++ B OP+ |
\----------------------------------------- Finland rules! ------------/
"And according to Occam's Toothbrush, we only need to optimise the most frequent
instructions."
- Teemu Kerola
Nov 13 '05 #16
On Tue, 2 Sep 2003 23:10:21 -0400,
Henry <he*****@knology.net> wrote:

"Irrwahn Grausewitz" <ir*****@freenet.de> wrote in message
news:62********************************@4ax.com...
"Henry" <he*****@knology.net> wrote in
<vl************@corp.supernews.com>:
<SNIP>
>Ok thanks, when I changed the way it was typed it worked much better..
>Strangly the array[x,y] came straight from the "Practical C" book.

If there are more flaws like this in the book, get a better one.
(Btw.: were the (void) casts for printf straight from that book, too?


Yes... it seemed strange to me that they would expect a return on printf


That's not strange, since printf() does return a value. Explicitly
casting it away like that, however, isn't really necessary. It used to
be done a lot to shut up warnings from lint about discarded return
values, but it isn't necessary to do.

Martien
--
|
Martien Verbruggen | The problem with sharks is that they are too
| large to get to the shallow end of the gene
| pool. -- Scott R. Godin
Nov 13 '05 #17
Henry <he*****@knology.net> wrote:
> Ok thanks, when I changed the way it was typed it worked much better..
> Strangly the array[x,y] came straight from the "Practical C" book.
Burn your book :-)

Well I started learning C using the K&R book but it assumed too much, so I
was told "Practical C" would be a much better book to go through because it
would be more in depth and would cover topics that K&R would seemingly skip
over. So far "PC" has been compeltly different.. using commands such as
scanf and fgets which K&R didn't even mention


You better have a another look at your K&R2 (I hope you have the second
edition), and go to section 7.4 (completely devoted to scanf()) and 7.7
(discusses fgets() and fputs()). K&R probably doesn't introduce these
functions earlier because you need to have understood about pointers
and arrays before you can use them. I guess that a lot of the questions
you see asked in clc why stuff like

char *my_string;
double my_float;
scanf( "%f %s", my_float, my_string );

does not work may be due to books introducing scanf() too early...

Regards, Jens
--
_ _____ _____
| ||_ _||_ _| Je***********@physik.fu-berlin.de
_ | | | | | |
| |_| | | | | | http://www.physik.fu-berlin.de/~toerring
\___/ens|_|homs|_|oerring
Nov 13 '05 #18
"Henry" <he*****@knology.net> wrote in
<vl************@corp.supernews.com>:
> Ok thanks, when I changed the way it was typed it worked much better..
> Strangly the array[x,y] came straight from the "Practical C" book.


Burn your book :-)

[snip]

--
Jeff


LOL

Well I started learning C using the K&R book but it assumed too much, so I
was told "Practical C" would be a much better book to go through because it
would be more in depth and would cover topics that K&R would seemingly skip
over. So far "PC" has been compeltly different.. using commands such as
scanf and fgets which K&R didn't even mention


Huh? You must own a very rare preliminary version of K&R! :)

In my copy of K&R2 fgets and (f)scanf are used frequently in
the examples. scanf has a section dedicated to it as well:
Chapter 7.4: Formatted Input - Scanf
And in 7.7 the source code for a possible fgets/fputs
implementation is given...
--
No sig today.
Nov 13 '05 #19
rb*@panix.com (Brett Frankenberger) wrote in message news:<bj**********@reader2.panix.com>...
In article <20***************************@mb-m23.aol.com>,
Bigdakine <bi*******@aol.comGetaGrip> wrote:

Heck, I'm interested to know how this even compiled.
(void)printf("%d ", array[x,y]);


Why wouldn't it? 'x,y' is a perfectly valid expression (equivalent to
'y'), and array[y] doesn't violate any constraints (and would even be
useful, defined behavior under some circumstances), so one wouldn't
expect compilation to fail. Of course, array[y] is type (pointer to
int), so attempting to print it with "%d" is undefined behavior.

-- Brett


I forgot about the "," operator.

Thanx. Be that as it may, if the intent is to print an element of a
2-d array, it should be written as [x][y]

Stuart
Nov 13 '05 #20

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

Similar topics

2
by: Fred Zwarts | last post by:
If I am right, members of a class that are const and not static must be initialized in the initialization part of a constructor. E.g. class C { private: const int I; public: C(); };
13
by: simondex | last post by:
Hi, Everyone! Does anyone know how to initialize an int array with a non-zero number? Thank You Very Much. Truly Yours, Simon Dexter
8
by: Peter B. Steiger | last post by:
The latest project in my ongoing quest to evolve my brain from Pascal to C is a simple word game that involves stringing together random lists of words. In the Pascal version the whole array was...
15
by: Charles Sullivan | last post by:
Assume I have a static array of structures the elements of which could be any conceivable mixture of C types, pointers, arrays. And this array is uninitialized at program startup. If later in...
3
by: kk_oop | last post by:
Hi. I recently wrote a simple little template that defines an array that checks attempts to use out of bounds indexes. The only problem is that it does provide the use array style value...
5
by: toton | last post by:
Hi, I can initialize an array of class with a specific class as, class Test{ public: Test(int){} }; Test x = {Test(3),Test(6)}; using array initialization list. (Note Test do NOT have a...
15
by: jamx | last post by:
How can you initialize an array, in the initialization list of a constructor ?? SomeClass { public: SomeClass() : *init here* { } private: int some_array; };
2
by: anon.asdf | last post by:
Hi! Q. 1) How does one write: sizeof(array of 5 "pointers to double") ??? I know that sizeof(pointer to an array of 5 doubles) can be written as: sizeof(double (*));
152
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 = { {...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
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,...

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.