473,836 Members | 1,599 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 #1
53 4573
"Tomás" <NU**@NULL.NULL > wrote:
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" ).
A char is _always_ a byte. What you mean is that you are assuming a char
(and therefore also a byte) to be equal to an octet.
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) );


*Boing* and here the demonstration crashes.

Never cast malloc(). It is not necessary. void *s can be freely
converted to and from any object pointer type.
Never use malloc() (or any other function, for that matter) without a
proper declaration in scope. It forces your compiler to assume that the
function returns an int, which malloc() clearly does not.

Note that the first error hides the second. The combination of the two
can result in garbage being assigned to your pointer.

As a matter of convenient maintenance, not a true error, it is more
dabble-proof to use sizeof *pointer rather than sizeof (type). If your
pointer's type changes, the first form stays correct, the second can
turn deceptively (and hiddenly!) broken.

All in all, that program should've looked like this:

#include <stdlib.h>

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

int* const pointer = malloc(5 * sizeof *pointer);
}

Anyway, the difference between pointers and arrays is most simply
demonstrated using the age[1]-old method of arrows and groups of boxes.

Richard

[1] I.e., in the computing world, a couple of decades
May 11 '06 #2
Tomás wrote:
Some programmers treat arrays just like pointers (and some even think that
they're exactly equivalent). I'm going to demonstrate the differences.


Some of these days you can also write an article demonstrating that integer
types are not floating point types. It will be another great contribution
to the progress of humanity.

--
Salu2

Inviato da X-Privat.Org - Registrazione gratuita http://www.x-privat.org/join.php
May 11 '06 #3
As a matter of convenient maintenance, not a true error, it is more
dabble-proof to use sizeof *pointer rather than sizeof (type). If your
pointer's type changes, the first form stays correct, the second can
turn deceptively (and hiddenly!) broken.

All in all, that program should've looked like this:

#include <stdlib.h>

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

int* const pointer = malloc(5 * sizeof *pointer);
}

Anyway, the difference between pointers and arrays is most simply
demonstrated using the age[1]-old method of arrows and groups of boxes.

Richard

[1] I.e., in the computing world, a couple of decades


Okay, I'm probably missing this. But say I have the following:

/*I omitted checking for NULL and using free*/

#include <stdio.h>
#include <stdlib.h>

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

int *q = malloc(sizeof *array);

return 0;
}
Now, I change
int array[5];

to

double array[5];

Wouldn't the sizeof double be truncated to the sizeof int? If so, the
wouldn't this create an additional bug?

Chad

May 11 '06 #4
Chad wrote:
As a matter of convenient maintenance, not a true error, it is more
dabble-proof to use sizeof *pointer rather than sizeof (type). If your
pointer's type changes, the first form stays correct, the second can
turn deceptively (and hiddenly!) broken.

All in all, that program should've looked like this:

#include <stdlib.h>

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

int* const pointer = malloc(5 * sizeof *pointer);
}

Anyway, the difference between pointers and arrays is most simply
demonstrated using the age[1]-old method of arrows and groups of boxes.

Richard

[1] I.e., in the computing world, a couple of decades


Okay, I'm probably missing this. But say I have the following:

/*I omitted checking for NULL and using free*/

#include <stdio.h>
#include <stdlib.h>

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

int *q = malloc(sizeof *array);

return 0;
}
Now, I change
int array[5];

to

double array[5];

Wouldn't the sizeof double be truncated to the sizeof int? If so, the
wouldn't this create an additional bug?


You have not followed the suggested practice of using sizeof *pointer
being assigned to. Your example should have been:
#include <stdlib.h>

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

int *q = malloc(sizeof *q);

return 0;
}

Or, if you want array and q to always be the same type, you could have used:
#include <stdlib.h>
int main(void) {
int array[5], *q = malloc(sizeof *q);

return 0;
}

I really can't see why you would think of using sizeof some other object.
--
Flash Gordon, living in interesting times.
Web site - http://home.flash-gordon.me.uk/
comp.lang.c posting guidelines and intro:
http://clc-wiki.net/wiki/Intro_to_clc

Inviato da X-Privat.Org - Registrazione gratuita http://www.x-privat.org/join.php
May 11 '06 #5
Chad wrote:
.... snip ...
Okay, I'm probably missing this. But say I have the following:

/*I omitted checking for NULL and using free*/

#include <stdio.h>
#include <stdlib.h>

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

int *q = malloc(sizeof *array);


There is no such thing as *array. array is an array of 5 integers,
not a pointer.

--
Some informative links:
news:news.annou nce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html
May 11 '06 #6
CBFalconer wrote:

Chad wrote:

... snip ...

Okay, I'm probably missing this. But say I have the following:

/*I omitted checking for NULL and using free*/

#include <stdio.h>
#include <stdlib.h>

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

int *q = malloc(sizeof *array);


There is no such thing as *array. array is an array of 5 integers,
not a pointer.

"array[0]" is the same as "*(array+0) " which simplifies to "*array".
--
+----------------------------------------------------------------+
| Charles and Francis Richmond richmond at plano dot net |
+----------------------------------------------------------------+
May 11 '06 #7
CBFalconer wrote:

Chad wrote:

int array[5];

int *q = malloc(sizeof *array);


There is no such thing as *array. array is an array of 5 integers,
not a pointer.


(*array) is an expression of type int.

The operand of sizeof is (*array), not (array),
so, array gets converted to a pointer.

--
pete
May 11 '06 #8
Charles Richmond wrote:
CBFalconer wrote:
Chad wrote:
>

... snip ...

Okay, I'm probably missing this. But say I have the following:

/*I omitted checking for NULL and using free*/

#include <stdio.h>
#include <stdlib.h>

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

int *q = malloc(sizeof *array);


There is no such thing as *array. array is an array of 5 integers,
not a pointer.


"array[0]" is the same as "*(array+0) " which simplifies to "*array".


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

--
Some informative links:
news:news.annou nce.newusers
http://www.geocities.com/nnqweb/
http://www.catb.org/~esr/faqs/smart-questions.html
http://www.caliburn.nl/topposting.html
http://www.netmeister.org/news/learn2quote.html
May 11 '06 #9
CBFalconer posted:

"array[0]" is the same as "*(array+0) " which simplifies to "*array".


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

Stop trolling and propogating misinformation.

"array" implicitly converts to a pointer to its first element ALL THE TIME
-- NOT just when passed as an argument to a function, NOT just when it's a
global variable, NOT just when you have porridge instead of cereal.

-Tomás
May 12 '06 #10

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

Similar topics

11
55628
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
1479
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
10198
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
3341
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
7929
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
3519
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
9825
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
10852
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
10553
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
10255
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...
0
9382
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...
0
6980
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
5651
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...
0
5829
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4459
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.