473,400 Members | 2,163 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,400 software developers and data experts.

new foo[42]

Hello,

in the last time I see a lot like:

float * foo = new float[42];

First question: This isn't right, isn't it?
It has to be:

float ** foo = new float[42]; ?????

Second Question
What is the difference to

float foo[42]; ??
Simon Adler

--
BOFH excuse #69:
knot in cables caused data stream to become twisted and kinked
Jul 22 '05 #1
10 1261

"Simon Adler" <si***@wohnheim.fh-wedel.de> wrote in message
Hello,

in the last time I see a lot like:

float * foo = new float[42];

First question: This isn't right, isn't it?
It is correct.
It has to be:

float ** foo = new float[42]; ?????
This isn't. Who told you this to be correct ? Try a compiler when in doubt.

Second Question
What is the difference to

float foo[42]; ??


The former allocates memory dynamically (i.e. at run time)

Sharad
Jul 22 '05 #2
Sharad Kala wrote:
"Simon Adler" <si***@wohnheim.fh-wedel.de> wrote in message
Hello,

in the last time I see a lot like:

float * foo = new float[42];

First question: This isn't right, isn't it?

It is correct.

It has to be:

float ** foo = new float[42]; ?????

This isn't. Who told you this to be correct ? Try a compiler when in doubt.

Second Question
What is the difference to

float foo[42]; ??

The former allocates memory dynamically (i.e. at run time)


All memory for objects is allocated at run-time.

The major difference not often recognised by programmers is that 'foo' has
the type 'array of 42 float' in the former case and 'pointer to float' in
the latter case. Other differences are _where_ the memory is allocated
(implementation-defined) and how long the object remains around (specified
by the Standard).

V
Jul 22 '05 #3
Simon Adler wrote:
[newbie questions]

Get yourself _Accelerated C++_ by Koenig and Moo.
Get yoruself _The C++ Language_ by Stroustrup.

Read these two books carefully and closely. Make sure
to try all the examples with your compiler.
Look through this group to find refs to the FAQ and read it.
Socks

Jul 22 '05 #4

"Simon Adler" <si***@wohnheim.fh-wedel.de> wrote in message
news:slrncs5fon.bo7.si***@wohnheim.fh-wedel.de...
Hello,

in the last time I see a lot like:

float * foo = new float[42];

First question: This isn't right, isn't it?
The statement is correct, at least as far as syntax is concerned. You're
allocating an array of 42 floats, and storing the address of the first
element of that array in the pointer foo (which is of the correct type:
float*).

Whether it is "right" or not depends on if that is what you wanted!
It has to be:

float ** foo = new float[42]; ?????
That is not correct syntax (as a compiler would tell you). You're trying to
store the address of the first element of an array of floats (a float*) into
a variable of type float**. A float* is not the same as a float**. Now, if
you had done this:

float** foo = new float*[42];

That WOULD be correct syntax, since now you're dynamically creating an array
of 42 float* pointers, and storing the address of the first pointer (which
would make it a float**) in your float** variable.

But again, it all depends upon what you WANT as to which is correct.

Second Question
What is the difference to

float foo[42]; ??


That's an array of 42 float values, called foo. While you can pass foo to a
function that wants a float* as a parameter, foo is not really a pointer,
it's the name of the array, and you don't have to later call delete[] on it
(and in fact, you CAN'T call delete[] on it, since it's not a pointer!).

-Howard
Jul 22 '05 #5

"Simon Adler" <si***@wohnheim.fh-wedel.de> wrote in message
news:slrncs5fon.bo7.si***@wohnheim.fh-wedel.de...
Hello,

in the last time I see a lot like:

float * foo = new float[42];

First question: This isn't right, isn't it?
Yes it's correct. It creates a type 'foo*'
('pointer to float') object, allocates an array of
42 type 'float' objects, and returns the address
of the first one ( foo[0] ), and stores that address
value in the pointer object 'foo'. Note however,
that none of the 42 type 'float' objects is
initialized, so they must be assigned valid
values in order to be able to access them
without undefined behavior.
It has to be:

float ** foo = new float[42]; ?????
No. Why do you feel it does?

Second Question
What is the difference to

float foo[42]; ??


The first form above dynamically allocates an array (which
means that the array 'lives' until you specifically deallocate
it with 'delete[]', or the program terminates). The form:

float foo[42];

defines either a 'static' (if this definition appears
at file scope) or 'automatic' (if this definition appears
at block scope) array of 42 type 'float' objects. In
the 'static' case, the array's lifetime is the duration
of program execution. Also, all 42 objects are zero-
intialized. In the 'automatic' case, the array's
lifetime is from its point of definition, up to the point
where the scope it's defined is exited. None of the
42 objects are intitialized, so evaluating any of them
results in undefined behavior. So in the 'automatic'
case, I recomment the form:

float foo[42] = {0}; /* Initializes all array members to zero */

(or specificy a list of initializers with values that make sense
for your application).

This will prevent inadvert evaluation of uninitialized
objects, and the resultant undefined behavior.

BTW I recommend not using 'new' and 'raw' pointers as
above without a compelling reason to do so. For 'collections'
of same-type objects, I recommend using a standard container
(e.g. vector) instead. The standard containers do all
their own memory management for you automatically. This
will reduce the possibility of memory leaks, corrupted
pointers, etc.

Which C++ book(s) are you reading?

-Mike
Jul 22 '05 #6
In article <11********************@f14g2000cwb.googlegroups.c om>,
Puppet_Sock wrote:
Simon Adler wrote:
[newbie questions]
Sorry, if this semms newbie, but I want to understand.
Get yourself _Accelerated C++_ by Koenig and Moo.
Get yoruself _The C++ Language_ by Stroustrup.

I'll have a look at those. Thanks

Simon

--
Support Bingo, keep Grandma off the streets.
Jul 22 '05 #7
In article <d4****************@newsread1.news.pas.earthlink.n et>,
Mike Wahler wrote:

About my first question I understand. Thanks a lot. I've no further
questions about that.

I know about static Array allocation, but I was not sure about the
difference to the new allocation. I don't saw it before. I prefered
to use calloc instead.

Sorry, if I ask newbie questions too, but I am curious again:

float * foo = (float *)malloc( 100 * sizeof(float));
is the same like
float * foo = new float[100];

Hope I don't understand the Initialisation behaivior wrong.
The Difference to the satic allocation is ok now.
BTW I recommend not using 'new' and 'raw' pointers as
above without a compelling reason to do so.
Please don't understand me in the wrong way. I don't use something
I do not unterstand. I saw this in an code and I was curious. Books
can tell me a lot about Standarts, and I am intrested to read them,
but I am interested in practical issues, too.
Which C++ book(s) are you reading?

I learned a lot from my Prof., but there I learned C, so I read:
Harbison, Samuel P. / Steele Jr., Guy L. : C - A Reference Manual

After that I'd some Projects which I need C++, so I read a book to
learn something about the Differences to C(in a short time):
Lippman, Stanley B. : Essential C++
Fast to read and enugh to complete the Project, but not to understand
the Full possiblities.

I am greatful for any advice!

Simon Adler
--
Support Bingo, keep Grandma off the streets.
Jul 22 '05 #8
Simon Adler wrote:
[Recently] I see a lot like:

float* foo = new float[42];

First question: This isn't right, isn't it?
It has to be:

float** foo = new float[42];

Second Question,
"What is the difference [from]

float foo[42];

?" cat main.cc #include <iostream>

int main(int argc, char* argv[]) {
float* foo = new float[42];
float bar[42];
std::cout << "sizeof(foo) = " << sizeof(foo) << std::endl;
std::cout << "sizeof(bar) = " << sizeof(bar) << std::endl;
return 0;
}
g++ -Wall -ansi -pedantic -o main main.cc
./main

sizeof(foo) = 4
sizeof(bar) = 168

foo is a pointer to the first float of a dynamically allocated array but
bar is an entire array of 42 objects of type float.
Jul 22 '05 #9
"Simon Adler" <si***@wohnheim.fh-wedel.de> wrote in message
news:slrncs6rep.rfp.si***@wohnheim.fh-wedel.de...
In article <d4****************@newsread1.news.pas.earthlink.n et>,
Mike Wahler wrote:

About my first question I understand. Thanks a lot. I've no further
questions about that.

I know about static Array allocation, but I was not sure about the
difference to the new allocation. I don't saw it before. I prefered
to use calloc instead.
You can if you like, and if it fits your needs. But
note a very important difference between using
'malloc/calloc/realloc and free' and using 'new/delete'
or 'new[]/delete[]', is that the 'malloc/calloc/realloc
and free' method will not invoke constructors and
destructors. For that you *must* use 'new/delete'
or 'new[]/delete[]'. If you're only allocating
built-in types (e.g. 'int', 'float', etc.) either
way will work OK.

Sorry, if I ask newbie questions too, but I am curious again:

float * foo = (float *)malloc( 100 * sizeof(float));
More idiomatic is:

float *foo = static_cast<float*>(malloc(100 * sizeof *foo));

(if you later change the type of 'foo', you needn't adjust
the invocation of 'malloc()').

Also you should prefer a symbolic name (i.e. define
a constant) to represeent the '100' rather than 'hard
coding' such 'magic' numbers. Much easier to maintain.
is the same like
float * foo = new float[100];
It's similar, but not the same. See above.

Hope I don't understand the Initialisation behaivior wrong.
The Difference to the satic allocation is ok now.
BTW I recommend not using 'new' and 'raw' pointers as
above without a compelling reason to do so.
Please don't understand me in the wrong way. I don't use something
I do not unterstand. I saw this in an code and I was curious. Books
can tell me a lot about Standarts, and I am intrested to read them,
but I am interested in practical issues, too.


But the problem with taking an arbitrary piece of code to
study (especially when you're not well-grounded in language
rules), is that you often won't be able to distinguish between
'correct' and 'incorrect' code (there seem to be many, many
coders out there who believe they know C++ but acutally do not).

Also many programs use implementation-specific features which
are not part of the standard language. Good books will allow
you to recognize these differences.
Which C++ book(s) are you reading? I learned a lot from my Prof., but there I learned C, so I read:
Harbison, Samuel P. / Steele Jr., Guy L. : C - A Reference Manual


Good book. For C, but not C++.

(Despite the very close syntax, C and C++ are not
as similar as many believe, e.g. in some cases the
exact same syntax will have different semantics between
the two languages)
After that I'd some Projects which I need C++, so I read a book to
learn something about the Differences to C(in a short time):
Lippman, Stanley B. : Essential C++
Pretty good one, imo.
Fast to read and enugh to complete the Project, but not to understand
the Full possiblities.
I am greatful for any advice!


[I'm an "English Lawyer" :-) ] that's "grateful".

If you're fairly experienced with C (or some other language(s))
I recommend starting C++ with this book: www.acceleratedcpp.com

Also, see the book review section at www.accu.org for peer
reviews and recommendations.

HTH,
-Mike


Jul 22 '05 #10

"Victor Bazarov" <v.********@comAcast.net> wrote in message
Sharad Kala wrote:
"Simon Adler" <si***@wohnheim.fh-wedel.de> wrote in message
Hello,

in the last time I see a lot like:

float * foo = new float[42];

First question: This isn't right, isn't it?

It is correct.

It has to be:

float ** foo = new float[42]; ?????

This isn't. Who told you this to be correct ? Try a compiler when in doubt.
Second Question
What is the difference to

float foo[42]; ??

The former allocates memory dynamically (i.e. at run time)


All memory for objects is allocated at run-time.


I guess I should have been more elaborate.
The major difference not often recognised by programmers is that 'foo' has
the type 'array of 42 float' in the former case and 'pointer to float' in
the latter case. Other differences are _where_ the memory is allocated
Nah..it's the other way round. Look again.
(implementation-defined) and how long the object remains around (specified
Yes, I specifically did not want to mention heap/stack etc as it is
implementation defined.
by the Standard).


The object in the former case stays around till the time a delete is called
or program terminates. For the latter case it will be till the scope of the
block where it is defined .

Sharad
Jul 22 '05 #11

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

Similar topics

24
by: Hung Jung Lu | last post by:
Hi, Does anybody know where this term comes from? "First-class object" means "something passable as an argument in a function call", but I fail to see the connection with "object class" or...
28
by: Daniel | last post by:
Hello =) I have an object which contains a method that should execute every x ms. I can use setInterval inside the object construct like this - self.setInterval('ObjectName.methodName()',...
5
by: vilhelm.sjoberg | last post by:
Hello, I am a resonably confident C programmer, but not very sure about the dark corners of C++. Recently, I had G++ give me a strange error. The program in question is in essence: struct...
37
by: Rajesh | last post by:
I was informed tht $SUBJECT was asked in M$ interview. Real imp. is no. of ways to achive it. mine sol. was.... int main() { if(printf("foo")) { ; } else { ; }
2
by: hotadvice | last post by:
hello all Consider this: Suppose we have a an array of structure declared as following in file1.c structure foo{ ....... .......
13
by: Andy Baxter | last post by:
Can anyone recommend a good online guide to using objects in javascript? The book I bought (DHTML Utopia) suggests using objects to keep the code clean and stop namespace clashes between different...
14
by: António Marques | last post by:
Hi! I don't think I've ever been here, so I assume I'm addressing a bunch of nice people. Can you help me? I don't think there's a solution, but who knows. The thing is, picture a large...
10
by: ravi | last post by:
Hi, i am a c++ programmer, now i want to learn programming in c also. so can anybody explain me the difference b/w call by reference and call by pointer (with example if possible).
30
by: kj | last post by:
My book (Flanagan's JavaScript: The Definitive Guide, 5th ed.) implies on page 111 that the following two constructs are equivalent: ( x.constructor == Foo ) and ( x instanceof Foo ) The...
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: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
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,...
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
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...
0
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,...

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.