473,626 Members | 3,467 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Learning pointers question

Hi all,
What is the difference between these two statements?
int* a = new int[8]
and
int a[8]

The reason I ask is because this
int len = sizeof(a) / sizeof(*a)
works for the second construct, but not the first.

Nov 24 '05 #1
8 1529
macawm wrote:
Hi all,
What is the difference between these two statements?
int* a = new int[8]
a is a pointer that is initialized with the address
of a dynamically allocated array of 8 ints.
and
int a[8];
a is an ARRAY of 8 ints (allocated wherever this statement
appears).
The reason I ask is because this
int len = sizeof(a) / sizeof(*a)
works for the second construct, but not the first.

Pointers are not arrays nor vice versa.

The size of a pointer is the same regardless of what value
you set it to and is unrelated to the size of the thing
it points to.

An array however, has a size that is the number of elements
in the array times the size of each element. Hence your
length test works fine to reverse that.

Pointers only really have the concept of pointing to one
thing. If you dynamically allocate an array, you'll have
to remember the size. Alternatively (and this is almost
certainly a better idea), use the standard vector class.

vector<int> a(8);

You can do things like:
a[3]
and you can ask the size by
a.size()

and you can size it with a variable (arrays only work with constant
sizes) and even resize it. You further don't have to remember
to free it or do special things when copying like you would for
dynamic allocations.
Nov 24 '05 #2
Hi,

int a[8] is created on the stack it ceases to exist when the function
returns ( well actually it points to memory that is likely to be
overwritten).

a variable with new is created on the heap (a bunch of memory located
somewhere independent of the function).

in the first case your expression yields:

sizeof integer pointer divided by sizeof where the pointer is pointing to
(i.e. an int)

the second case
the sizeof of the array (8 times sizeof int) divided by sizeof int ( a
becomes pointer to array of int so sizeof *a is sizeof int)

--
Regards, Ron AF Greve

http://moonlit.xs4all.nl

"macawm" <ma****@gmail.c om> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
Hi all,
What is the difference between these two statements?
int* a = new int[8]
and
int a[8]

The reason I ask is because this
int len = sizeof(a) / sizeof(*a)
works for the second construct, but not the first.

Nov 24 '05 #3

"macawm" <ma****@gmail.c om> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
| Hi all,
| What is the difference between these two statements?
| int* a = new int[8]
| and
| int a[8]
|
| The reason I ask is because this
| int len = sizeof(a) / sizeof(*a)
| works for the second construct, but not the first.
|

The first statement allocates the array on the heap and the second is
allocated on the stack. As far as int *a is concerned, consider writing
those 2 statements like so:

int *p = new int[10];
delete [] p;

int a[10];

and keep in mind that p is a pointer to an integer, not an array.

That len statement should be:

int len = sizeof(a) / sizeof(int);

which only applies to the stack allocated container.

and since p is not pointing to an array:

const int len(10);
int *p = new int[len];
std::cout << "len = " << len << std::endl;
delete [] p;

___
Vectors to the rescue:

std::vector<int > v(10, 0); // an instant vector of 10 elements preset to
0
std::cout << v.size() << std::endl;

std::vector<int > *p = v;

now p *is really* pointing to a std::vector of integers. Lets go one
step further, the following works regardless of what size the vector is
at runtime. Using classic STL with a reference instead of dumb pointers.

#include <iostream>
#include <ostream>
#include <vector>

template< class T >
void display(const std::vector< T >& v) // ref to a std::vector<T>
{
std::cout << "\nstd::vec tor with " << v.size() << " elements.\n";
for(int i = 0; i < v.size();++i) { std::cout << v[i] << " "; }
std::cout << std::endl;
}

int main()
{
std::vector<int > vn(10, 0);
display<int>(vn ); // templated for integers

std::vector<dou ble> vd(5, 1.1);
display<double> (vd); // templated for doubles

vd.push_back(1. 2);
vd.push_back(1. 3);
display<double> (vd);

return 0;
}

/*

std::vector with 10 elements.
0 0 0 0 0 0 0 0 0 0

std::vector with 5 elements.
1.1 1.1 1.1 1.1 1.1

std::vector with 7 elements.
1.1 1.1 1.1 1.1 1.1 1.2 1.3

*/

Think about the astronomical amount of work required to duplicate that
project using primitive arrays. Note that i could have used std::strings
or for that matter any user-defined class(with a defined friend
operator<<).

std::vector< std::string > vs(1000, "string");
display(vs);
std::vector< MyClass > my_v(100, MyClass(...));
display(my_v);

And you wouldn't need to modify display() in any way.
Nov 25 '05 #4
Hi all,
What is the difference between these two statements?
int* a = new int[8]
and
int a[8]

The reason I ask is because this
int len = sizeof(a) / sizeof(*a)
works for the second construct, but not the first.

Here's a link to a C++Course explaining all the stuff around pointers and
references (and more):

http://www.vias.org/cppcourse/chap16_02.html

Just browse through the pages or use the index, there is plenty of
introductory material..

Hope this helps,

Hans
--
=============== =============== =======
Hans Lohninger
EPINA GmbH - Software Development Lohninger
www.lohninger.com
mailto:of****@e pinasoft.com
fax: +43-2233-541945
=============== =============== ========
Nov 25 '05 #5

Peter_Julian wrote:
"macawm" <ma****@gmail.c om> wrote in message
news:11******** **************@ g43g2000cwa.goo glegroups.com.. .
| Hi all,
| What is the difference between these two statements?
| int* a = new int[8]
| and
| int a[8]
|
| The reason I ask is because this
| int len = sizeof(a) / sizeof(*a)
| works for the second construct, but not the first.
<snip>
That len statement should be:

int len = sizeof(a) / sizeof(int);


No it shouldn't

If you want to use this technique to measure the size of an array, the
OP's code is better. If the array type is changed to, for example

short a[8];

you have to remember to change your len statement to

int len = sizeof(a) / sizeof(short);

or you will get the wrong answer (unless short and int happen to be the
same size - but then what about double ...)

The OP's code is more robust. You can change they type of the array and
the len statement will still be correct as written.

Gavin Deane

Nov 25 '05 #6
* Hans Lohninger:
Hi all,
What is the difference between these two statements?
int* a = new int[8]
and
int a[8]

The reason I ask is because this
int len = sizeof(a) / sizeof(*a)
works for the second construct, but not the first.

Here's a link to a C++Course explaining all the stuff around pointers and
references (and more):

http://www.vias.org/cppcourse/chap16_02.html

Just browse through the pages or use the index, there is plenty of
introductory material..


It's not a good idea to post links to garbage.

<quote>
#include <iostream.h>

int main()
{
int someNumber = 12345;
int* ptrSomeNumber = &someNumber;

cout << "someNumber = " << someNumber << endl;
cout << "ptrSomeNum ber = " << ptrSomeNumber << endl;

return 0;
}

If you compiled and ran the above code, you would have the variable
someNumber output 12345 while ptrSomeNumber would output some
hexadecimal number (addresses in memory are represented in hex).
</quote>

The first line quoted says: _stay away_.

And the last line quoted says the same.

--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 25 '05 #7
Thanks to everyone. Your replies were to the point and fully explained
what I was missing. I didn't fully realize the implications of
dynamically allocating arrays. And I do agree with those that suggested
Vector, it seems to be a much nicer beast.

I was under the assumption that arrays are pointers.
int a[8]
*a or *(a+1) or *(a+n) will give the first, second, and nth element
of the array by dereferencing a's address.
Is this just wrong or am I still missing something?

Nov 25 '05 #8
* macawm:

I was under the assumption that arrays are pointers.
int a[8]
*a or *(a+1) or *(a+n) will give the first, second, and nth element
of the array by dereferencing a's address.
Is this just wrong or am I still missing something?


An array decays to a pointer to its first element in the cases you list.
--
A: Because it messes up the order in which people normally read text.
Q: Why is it such a bad thing?
A: Top-posting.
Q: What is the most annoying thing on usenet and in e-mail?
Nov 25 '05 #9

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

Similar topics

7
1764
by: Ryan Walker | last post by:
Hi, I'm getting started with python and have almost zero programming experience. I'm finding that there are tons of tutorials on the internet -- such as the standard tutorial at python.org -- that tell you all about the language. That is, what are the methods, functions, modules, syntax, punctuation, etc. No problem there! Meanwhile, I'm finding that there is very little (that I can find) about how to do basic logistical things related...
4
1821
by: newsock | last post by:
1. What to do to force an auto_ptr release the object it pointing at before reaching the end of the scope it resides? 2. If a class is defined as: class Student { int nAge; int nID; char sAddress;
17
1619
by: Javier | last post by:
Hi I'm trying to learn how to use pointers with a little example. I did: void main(int argc, char* argv) { char algo = "Algo mas"; char * p = algo;
1
1611
by: ketema | last post by:
Hello, I was wondering if someone could help me with a function I am trying to write. The purpose of the function is to read in text from a file in the following format: FIRSTNAME LASTNAME SCORE SCORE SCORE SCORE example: Karen Smith 100 100 100 100 John Oliver 78 90 65 51
1
9623
by: David Van D | last post by:
Hi there, A few weeks until I begin my journey towards a degree in Computer Science at Canterbury University in New Zealand, Anyway the course tutors are going to be teaching us JAVA wth bluej and I was wondering if anyone here would be able to give me some tips for young players such as myself, for learning the language. Is this the best Newsgroup for support with JAVA?
36
2513
by: utab | last post by:
Dear, I have experince in C( numerical projects, like engineering problems, scientific applications) I have the basic notion of C++ also, I have read Accelerated C++ until Chapter 7, however it seems that it discusses the std and the other part of the language with your own abstractions. Is that better to read a book first on the basic concepts of C++ language (but not the C part) that gives the basics as if the reader is a beginner...
26
2957
by: mfasoccer | last post by:
I am sorry if this is an inappropriate place to put this post, if so please delete it. I am wondering about a few things. Do you guys recommend learning C as a second language, as someone who already knows java very well. And what is the best way to learn C, books, tutorials, or what? Thanks, any response would be great.
7
2379
by: Hal Vaughan | last post by:
I have a problem with port forwarding and I have been working on it for over 2 weeks with no luck. I have found C programs that almost work and Java programs that almost work, but nothing that does what I need. I've even tried writing a port forwarder in Java and found problems that nobody seems to have the answer to in forums. I need to make it work essentially the same on both Windows and Linux. There is one program, in C, that...
6
1486
by: JoeC | last post by:
I understand the basics of pointers, they point to memory locations. I would like to know resources for learning all about poters. I am having some problems erasing elements of pointers from a vector. I wold like to know where I can get some in depth information on how to use pointers in various situations. It seems that all most books have to say about pointers is that they point to memory locations. Some even say they are...
0
8707
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
8641
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
8510
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
7199
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
4093
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
4202
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2628
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
1
1812
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
2
1512
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.