473,785 Members | 2,618 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Array and Pointer Tutorial

Some programmers treat arrays just like pointers (and some even think that
they're exactly equivalent). I'm going to demonstrate the differences.

Firstly, let's assume that we're working on a platform which has the
following properties:

1) char's are 8-Bit. ( "char" is synomonous with "byte" ).
2) int's are 32-Bit. ( sizeof(int) == 4 ).
3) Pointers are 64-Bit. ( sizeof(int*) == 8 ).
First let's make two declarations:

int main(void)
{
int array[5];

int* const pointer = (int*)malloc( 5 * sizeof(int) );
}
Now I'll demonstrate how "array" and "pointer" are different:
I'll start off with simple analgous expressions:

=============== =============== =============== =============== =============== =
| Expression | Type and Access Specifiers | That in English |
=============== =============== =============== =============== =============== =
| | | |
| array | int[5] | An array of five int's.|
| | | |
|---------------------------------------------------------------------------
| | |A const pointer which |
| pointer | int* const |points to a modifiable |
| | |int. |
|--------------------------------------------------------------------------|
| | |A const pointer which |
| &array | int (* const)[5] |points to a modifiable |
| | |array of five int's. |
|--------------------------------------------------------------------------|
| | |A const pointer, which |
| &pointer | int* const* const |points to a const |
| | |pointer, which points to|
| | |a modifiable int. |
=============== =============== =============== =============== =============== =
Here's how "sizeof" works with them:
=============== =============== =============== ==============
| Expression | sizeof( exp ) | But Why? |
=============== =============== =============== ==============
| | | |
| array | 20 | It's five int's. |
| | (5 * 4) | |
|---------------------------------------------------------|
| | | |
| pointer | 8 | It's just a pointer.|
| | (just 8) | |
|---------------------------------------------------------|
| | | |
| &array | 8 | It's just a pointer.|
| | (just 8) | |
|----------------------------------------------------------
| | | |
| &pointer | 8 | It's just a pointer.|
| | | |
| | (just 8) | |
=============== =============== =============== ==============
Okay next thing to discuss is the usage of square brackets, and the
dereference operator. The two of these are to be used by pointers only. So
how come we can use them with arrays, as follows?:

array[0] = 4;

*array = 6;

The reason is that an expression of the following type:

int[5]

can implicitly convert to an expression of the following type:

int* const

What it does is convert to a pointer to the first element of the array.
Therefore, the first example:

array[0] = 4;

implicitly converts "array" to a normal pointer, then uses chain brackets to
access memory at a certain offset from the original address.

Also the second example:

*array = 6;

implicitly converts "array" to a normal pointer, then dereferences it.
NOTE: You must remember that an array implicitly converts to a pointer to
its first element, NOT to a pointer to the array. This fact has a few
implications. Here's one such implication:
*(array + 3) = 6;
What the above line of code does is the following:

1) Implicitly converts "array" to an: int* const
2) Adds 3 * sizeof(int) to the address.
3) Dereferences the resulting pointer, and assigns 6 to it.
If "array" implicitly converted to: int (*)[5]
rather than a pointer to the first element, then Step 2 above would be
different, specifically:
2) Adds 3 * sizeof( int[5] ) to the address.
And we know that sizeof(int[5]) is 20 on this platform (not 8!).
So you may ask, "What's the point in having a pointer to an array?" -- well
here's where it may come in handy:
void SomeFunc ( int (* const p_array)[5] )
{
(*p_array)[0] = 99;
(*p_array)[1] = 98;
(*p_array)[2] = 97;
(*p_array)[3] = 96;
(*p_array)[4] = 95;

/* This function won't accept an array of any
other size! */
}
And here's a C++-specific example with references:

void SomeFunc ( int (&array)[5] )
{
array[0] = 99;
array[1] = 98;
array[2] = 97;
array[3] = 96;
array[4] = 95;

/* This function won't accept an array of any
other size! */
}
Also in C++, you can exploit the use of templates:

template<class T, unsigned long len>
void KeepCopy( const T (&array)[len] )
{
static my_array[len];

/* Do some other stuff */
}
I've posted this to a few newsgroups, so if you'd like to reply, please post
to comp.lang.c because it's the common denominator. If your post is C++-
specific, the please post to comp.lang.c++.

Did I leave anything out?

-Tomás

[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.m oderated. First time posters: Do this! ]
--
comp.lang.c.mod erated - moderation address: cl**@plethora.n et -- you must
have an appropriate newsgroups line in your header for your mail to be seen,
or the newsgroup name in square brackets in the subject line. Sorry.
May 11 '06
53 4567

Keith Thompson wrote:
"Nelu" <ta********@gma il.com> writes:
Nelu wrote:
Keith Thompson wrote: <snip>
> Passing it as a parameter is irrelevant.

<snip>

I'm not sure how irrelevant it is. Check this code:

void foo(char b[]) {
b++;
printf("%ld\t%l d\n",sizeof(b), sizeof(char*));
}


b is not an array; it's a pointer object. And it's not a const
object; it's merely initialized to the value of the actual argument.

In a parameter declaration, "char b[]" is merely an alias for "char *b".
This is independent of the rules for implicit conversion of array
names to pointer values.

Also, "%ld" is not the correct format for a size_t. You can use "%zu"
if your library conforms to C99, or you can convert the operand to
the expected type:
printf("%d\t%d\ n", (int)sizeof b, (int)sizeof(cha r*));
int main(void) {
char arr[10];
foo(arr);


Here arr is converted to a pointer value, equivalent to &arr[0].
This value is passed to foo and copied to b.
printf("%ld\n", sizeof(arr));

return 0;
}

[snip]


I didn't use %zu (although it works on my gcc) just in case someone
tries it on Turbo C :-). I forgot to cast, though, and -Wall didn't say
anything, probably because they are the same type.

The example was just to show that b (in foo) is a pointer object in
accordance with what CBFalconer was saying.
--
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.


May 14 '06 #41

Nelu wrote:
<snip>
--
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.


Sorry, I forgot to snip your signature from my previous post and paste
mine. I guess this is a sign I should go to sleep :-).

--
Ioan - Ciprian Tandau
tandau _at_ freeshell _dot_ org (hope it's not too late)
(... and that it still works...)

May 14 '06 #42
Nelu wrote:

Keith Thompson wrote:
CBFalconer <cb********@yah oo.com> writes: <snip>

When array is passed as a parameter, which this one isn't.


Sorry, you've blown this one.

An expression of array type is
implicitly converted to a pointer to its
first element *unless*:
It's the operand of a sizeof operator, or
It's the operand of a unary "&" operator, or
It's a string literal used to initialize an array.

Passing it as a parameter is irrelevant.

Forgive me, but I still think CBFalconer is right.


It's time to quote the standard:

N869
6.3.2 Other operands
6.3.2.1 Lvalues and function designators

[#3] Except when it is the operand of the sizeof operator or
the unary & operator, or is a string literal used to
initialize an array, an expression that has type ``array of
type'' is converted to an expression with type ``pointer to
type'' that points to the initial element of the array
object and is not an lvalue.
--
pete
May 14 '06 #43
pete wrote:

Nelu wrote:

Keith Thompson wrote:
CBFalconer <cb********@yah oo.com> writes: <snip>
>
> When array is passed as a parameter, which this one isn't.

Sorry, you've blown this one.

An expression of array type is
implicitly converted to a pointer to its
first element *unless*:
It's the operand of a sizeof operator, or
It's the operand of a unary "&" operator, or
It's a string literal used to initialize an array.

Passing it as a parameter is irrelevant.

Forgive me, but I still think CBFalconer is right.


It's time to quote the standard:


I see I already did this on Thursday.
What's the problem, Nelu?
N869
6.3.2 Other operands
6.3.2.1 Lvalues and function designators

[#3] Except when it is the operand of the sizeof operator or
the unary & operator, or is a string literal used to
initialize an array, an expression that has type ``array of
type'' is converted to an expression with type ``pointer to
type'' that points to the initial element of the array
object and is not an lvalue.


--
pete
May 14 '06 #44
pete posted:
[#3] Except when it is the operand of the sizeof operator or
the unary & operator, or is a string literal used to
initialize an array, an expression that has type ``array of
type'' is converted to an expression with type ``pointer to
type'' that points to the initial element of the array
object and is not an lvalue.


The reason they can put that in the Standard is that they've thought up of
every conceivable place where you can use an array as an array -- there's
only three such places, so it was handy to list them all.

In C++, we treat the array-to-pointer conversion just like any other
implicit conversion (e.g. char to int).

If we have a char:

char k;

It will remain as a char unless it needs to convert. For example:

void TakesAnInt( int r ) {}

int main(void) { char k; TakesAnInt(k); }

Just because a "char" can implicitly convert to an "int" doesn't mean
"char" is any less of a fully-fledged object type.

If we were able to pass arrays by value in C, then they'd have to remove
that paragraph from the Standard (or perhaps add the fourth instance where
you can use an array as an array).

In C++, we have references, and we can pass arrays by reference, so we tend
to look at it from the opposite viewpoint of C programmers.
Instead of thinking:
"When is an array actually an array, instead of being a pointer?"

We think:
"When does the array decay to a pointer?"

The most obvious place where we need to convert from array to pointer is by
the dereference operator:

*array /* You can't dereference an array, so it has
to become a pointer to its first element */
or by block brackets:

array[5] = 2; /* You can't use block-brackets with an array,
so it has to become a pointer to its first
element. */

Or by arithmetic:

array + 3 /* You can't use '+' with an array, so it has to
become a pointer to its first element */

Now that we know that an array will always be an array unless it needs to
convert to a pointer, we can pass arrays by reference:

void SomeFunc( int (&array)[20] )
{

}

int main()
{
int array[20];

SomeFunc( array );
}

The dandy thing about this way of thinking is that it works perfectly for C
aswell.

A char is a char, not an int (but it's more than happy to convert if it
needs to).

An array is an array, not a pointer (but it's more than happy to convert if
it needs to).

As C++ is constantly being developed and expanded upon, it's more
appropriate to state where an array decays to a pointer, rather than where
an array actually stays as an array.

Moral of the story: An array is an array -- not a pointer.

-Tomás
May 14 '06 #45
"Tomás" wrote:
pete posted:
[#3] Except when it is the operand of the sizeof operator or
the unary & operator, or is a string literal used to
initialize an array, an expression that has type ``array of
type'' is converted to an expression with type ``pointer to
type'' that points to the initial element of the array
object and is not an lvalue.


The reason they can put that in the Standard is that they've thought
up of every conceivable place where you can use an array as an array
-- there's only three such places, so it was handy to list them all.

In C++, we treat the array-to-pointer conversion just like any other
implicit conversion (e.g. char to int).


if you look closely you will see that this newsgroup is
comp.lang.c, not comp.lang.c++.

--
"If you want to post a followup via groups.google.c om, don't use
the broken "Reply" link at the bottom of the article. Click on
"show options" at the top of the article, then click on the
"Reply" at the bottom of the article headers." - Keith Thompson
More details at: <http://cfaj.freeshell. org/google/>
Also see <http://www.safalra.com/special/googlegroupsrep ly/>
May 14 '06 #46
CBFalconer wrote:

"Tomás" wrote:
pete posted:
if you look closely you will see that this newsgroup is
comp.lang.c, not comp.lang.c++.


I looked at the original post and found:

"I've posted this to a few newsgroups,
so if you'd like to reply,
please post to comp.lang.c
because it's the common denominator.
If your post is C++-specific,
the please post to comp.lang.c++."

I think it was a mistake to post here.

Elsewhere on this thread he quoted a part of the C++ standard
and refered to it as "the Standard".

--
pete
May 15 '06 #47
Tomás wrote:
In C++, we treat the array-to-pointer conversion just like any other
implicit conversion (e.g. char to int).


In C, there is no typical implicit conversion for your phrase
"just like any other implicit conversion", to refer to.

The rules for implicit conversion varry by type.
There are different rules for the implicit conversions of
expressions of:
function type,
array type,
arithmetic type lower ranking than int,
other arithmetic types,
pointer types.

--
pete
May 15 '06 #48
On 13 May 2006 23:22:09 -0700, "Nelu" <ta********@gma il.com> wrote:

Nelu wrote:
<snip>
> --
> 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.


Sorry, I forgot to snip your signature from my previous post and paste
mine. I guess this is a sign I should go to sleep :-).


It's a sign that you should use a newsreader that does it for you <g>.

--
Al Balmer
Sun City, AZ
May 15 '06 #49
On Fri, 12 May 2006 20:54:13 -0400, "Rod Pemberton"
<do*********@bi tfoad.cmm> wrote:

(in a reply to Richard Heathfield.)

The argument makes sense. Have you ever programmed? In C?


Heh. I suggest that you search both Google and Google Groups for
"Richard Heathfield". In quotes, to keep the hits to 50,000 or so.

You might also find his web site educational, on a much broader range
of topics.

--
Al Balmer
Sun City, AZ
May 15 '06 #50

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

Similar topics

11
55592
by: Pontus F | last post by:
Hi I am learning C++ and I'm still trying to get a grip of pointers and other C/C++ concepts. I would appreciate if somebody could explain what's wrong with this code: ---begin code block--- #include "stdio.h" #include "string.h" void printText(char c){
7
1477
by: Piotre Ugrumov | last post by:
I have tried to write the class Student(Studente), Teacher(Docente). This classes derive from the class Person. In a class university(facoltà). I have tried to create an array of Student and an array of Teacher, but the compiler give me an error. How can I do to go on? Here I have copied the Student, Teacher and University classes. Thanks Student class:
58
10181
by: jr | last post by:
Sorry for this very dumb question, but I've clearly got a long way to go! Can someone please help me pass an array into a function. Here's a starting point. void TheMainFunc() { // Body of code... TCHAR myArray; DoStuff(myArray);
2
3336
by: James | last post by:
Hi, I'm hoping someone can help me out. If I declare a class, eg. class CSomeclass { public: var/func etc..... private varfunc etc..
2
7926
by: Newsgroup Posting ID | last post by:
i'm new to c and have gotten my program to run but by passing hardcoded array sizes through the routines, i want to make the array extendable by using realloc but i'd be doing it two routines down, i need to figure out how to pass the array such that i know how many elements are in it before i realloc and that the array gets passed back up the routines in tact. i've used sizeof but it only works in the first routine, the 2nd and 3rd...
1
617
by: Tomás | last post by:
Some programmers treat arrays just like pointers (and some even think that they're exactly equivalent). I'm going to demonstrate the differences. Firstly, let's assume that we're working on a platform which has the following properties: 1) char's are 8-Bit. ( "char" is synomonous with "byte" ). 2) int's are 32-Bit. ( sizeof(int) == 4 ). 3) Pointers are 64-Bit. ( sizeof(int*) == 8 ).
6
3518
by: M Turo | last post by:
Hi, I was wondering if anyone can help. I'm want to pre-load a 'table' of function pointers that I can call using a its arrayed index, eg (non c code example) pFunc = func_A; pFunc = func_B;
0
9645
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
10341
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
10155
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...
0
9954
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
1
7502
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
5383
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
4054
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
2
3656
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2881
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.