I'm learning C++ from C++ Primer Plus 5th edition. I'm struggling at
the moment with declaring an array of three structures by using 'new' to
allocate memory. (this is one of the programming exercises at the end
of each chapter). My attempt is as per below. I get a compile error
indicating that -
"base operand of '->' has no pointer type 'candybar' "
// Q-09.cpp -- Question 9
#include <iostream>
struct candybar
{
//char brand[20];
std::string brand; //in this context - must use std::string
float weight;
int calories;
};
int main()
{
using namespace std;
candybar * snack = new candybar[3];
snack[0]->brand = "Mocha Munch"; // above error starts here
snack[0]->weight = 2.3;
snack[0]->calories = 350;
snack[1]->brand = "Crunchie";
snack[1]->weight = 1.9;
snack[1]->calories = 400;
snack[2]->brand = "Mars Bar";
snack[2]->weight = 4.5;
snack[2]->calories = 200;
cout << endl;
cout << "Snack brand : " << snack[0]->brand << endl;
cout << "Snack weight : " << snack[0]->weight << endl;
cout << "Snack calories : " << snack[0]->calories << endl;
cout << "Snack brand : " << snack[1]->brand << endl;
cout << "Snack weight : " << snack[1]->weight << endl;
cout << "Snack calories : " << snack[1]->calories << endl;
cout << "Snack brand : " << snack[2]->brand << endl;
cout << "Snack weight : " << snack[2]->weight << endl;
cout << "Snack calories : " << snack[2]->calories << endl;
delete snack;
return 0;
}
Any help would be appreciated, I really can't see why this shouldn't
work. I read the chapter umpteen times but I must be missing something.
Steve Taylor
Melbourne, Australia. 14 1974
"Steven Taylor" <ne******@super jacent.net> wrote in message
news:42******** *************** @news.optusnet. com.au I'm learning C++ from C++ Primer Plus 5th edition. I'm struggling at the moment with declaring an array of three structures by using 'new' to allocate memory. (this is one of the programming exercises at the end of each chapter). My attempt is as per below. I get a compile error indicating that -
"base operand of '->' has no pointer type 'candybar' "
// Q-09.cpp -- Question 9 #include <iostream> struct candybar { //char brand[20]; std::string brand; //in this context - must use std::string float weight; int calories; }; int main() { using namespace std; candybar * snack = new candybar[3];
snack[0]->brand = "Mocha Munch"; // above error starts here snack[0]->weight = 2.3; snack[0]->calories = 350;
Replace all of the -> operators with the . operator.
snack is a pointer, but using the subscript operator dereferences the
pointer. Thus snack[0] is of type candybar, not pointer to candybar.
--
John Carson
John Carson wrote: "Steven Taylor" <ne******@super jacent.net> wrote in message news:42******** *************** @news.optusnet. com.au
I'm learning C++ from C++ Primer Plus 5th edition. I'm struggling at the moment with declaring an array of three structures by using 'new' to allocate memory. (this is one of the programming exercises at the end of each chapter). My attempt is as per below. I get a compile error indicating that -
"base operand of '->' has no pointer type 'candybar' "
// Q-09.cpp -- Question 9 #include <iostream> struct candybar { //char brand[20]; std::string brand; //in this context - must use std::string float weight; int calories; }; int main() { using namespace std; candybar * snack = new candybar[3];
snack[0]->brand = "Mocha Munch"; // above error starts here snack[0]->weight = 2.3; snack[0]->calories = 350; Replace all of the -> operators with the . operator.
snack is a pointer, but using the subscript operator dereferences the pointer. Thus snack[0] is of type candybar, not pointer to candybar.
Thanks for your hlep John, it certainly compiled ok.
Steve.
Steven Taylor wrote: I'm learning C++ from C++ Primer Plus 5th edition. I'm struggling at the moment with declaring an array of three structures by using 'new' to allocate memory. (this is one of the programming exercises at the end of each chapter). My attempt is as per below. I get a compile error indicating that -
"base operand of '->' has no pointer type 'candybar' "
// Q-09.cpp -- Question 9 #include <iostream> struct candybar { //char brand[20]; std::string brand; //in this context - must use std::string float weight; int calories; }; int main() { using namespace std; candybar * snack = new candybar[3];
snack[0]->brand = "Mocha Munch"; // above error starts here
Your problem is here.
It is the way array indexing is defined in C++
a[index] is equivalent to *(a_as_ptr+inde x)
where a_as_ptr denotes a pointer to the first element of the array.
What you wanted to write was:
snack pointer
snack+0 index offset of index 0 to that pointer
*(snack+0) object at the index offset to that pointer
(*(snack+0)).br and the brand component of the object at the index
offset to that pointer
Due to the way array indexing is defined you can replace parts of the last expression.
(*(snack+0)).br and is equivalent to
snack[0].brand
So in short:
Even if snack is a pointer, snack[0] is no longer of pointer type, but is already
the object in the array. Therefore you don't use ->, but simply access the component
directly with a '.' operation.
--
Karl Heinz Buchegger kb******@gascad .at
Karl Heinz Buchegger wrote:
snip Your problem is here. It is the way array indexing is defined in C++
a[index] is equivalent to *(a_as_ptr+inde x)
where a_as_ptr denotes a pointer to the first element of the array.
What you wanted to write was:
snack pointer snack+0 index offset of index 0 to that pointer *(snack+0) object at the index offset to that pointer (*(snack+0)).br and the brand component of the object at the index offset to that pointer
Due to the way array indexing is defined you can replace parts of the last expression.
(*(snack+0)).br and is equivalent to
snack[0].brand
So in short: Even if snack is a pointer, snack[0] is no longer of pointer type, but is already the object in the array. Therefore you don't use ->, but simply access the component directly with a '.' operation.
Thanks, much appreciated.
Steve Taylor
"John Carson" <jc************ ****@netspace.n et.au> ????
news:42******** *************** @un-2park-reader-02.sydney.pipen etworks.com.au. .. "Steven Taylor" <ne******@super jacent.net> wrote in message news:42******** *************** @news.optusnet. com.au I'm learning C++ from C++ Primer Plus 5th edition. I'm struggling at the moment with declaring an array of three structures by using 'new' to allocate memory. (this is one of the programming exercises at the end of each chapter). My attempt is as per below. I get a compile error indicating that -
"base operand of '->' has no pointer type 'candybar' "
// Q-09.cpp -- Question 9 #include <iostream> struct candybar { //char brand[20]; std::string brand; //in this context - must use std::string float weight; int calories; }; int main() { using namespace std; candybar * snack = new candybar[3];
snack[0]->brand = "Mocha Munch"; // above error starts here snack[0]->weight = 2.3; snack[0]->calories = 350;
Replace all of the -> operators with the . operator.
snack is a pointer, but using the subscript operator dereferences the pointer. Thus snack[0] is of type candybar, not pointer to candybar.
-- John Carson
=============== =============== =============== =====
This Programme has a litte problem.First using string class ,you must use
headfile <string>
The other hand,I suggest you'd better use form like string a (" ") to
initiate variable of string class.
"Karl Heinz Buchegger" <kb******@gasca d.at> wrote in message > So in short: Even if snack is a pointer, snack[0] is no longer of pointer type, but is already the object in the array. Therefore you don't use ->, but simply access the component directly with a '.' operation.
Really? Wow...that's just strange. I guess I've never used an array of
pointers like that, because I sure didn't know this. (I tend to use vectors
nowadays for most dynamic array uses.)
So, suppose I actually _need_ a pointer from that array. How do I get it?
Like this?
candybar* pBar = &(snack[i]); // Like this?
That sure seems odd.
Somehow, I thought I'd used this kind of notation before somewhere:
(snack[i])->name = "Snickers";
Would that work?
-Howard
"Howard" <al*****@hotmai l.com> wrote in message
news:CN******** ***********@bgt nsc04-news.ops.worldn et.att.net "Karl Heinz Buchegger" <kb******@gasca d.at> wrote in message > So in short: Even if snack is a pointer, snack[0] is no longer of pointer type, but is already the object in the array. Therefore you don't use ->, but simply access the component directly with a '.' operation.
Really? Wow...that's just strange. I guess I've never used an array of pointers like that, because I sure didn't know this. (I tend to use vectors nowadays for most dynamic array uses.)
There is no array of pointers, just a pointer to an dynamically allocated
array. The pointer name functions just the same as the name of a statically
allocated array in terms of accessing elements of the array.
So, suppose I actually _need_ a pointer from that array. How do I get it? Like this?
candybar* pBar = &(snack[i]); // Like this?
snack is a pointer, as is snack + i, so you can write:
candybar* pBar = snack + i;
That sure seems odd.
Not to me. Using a subscript on a pointer is equivalent to dereferencing
the pointer. To make the point clear, consider:
int x = 1;
int *ptr = &x;
Then ptr[0] is the same as *ptr, i.e., it is equivalent to x.
Somehow, I thought I'd used this kind of notation before somewhere:
(snack[i])->name = "Snickers";
Would that work?
No.
--
John Carson
"John Carson" <jc************ ****@netspace.n et.au> wrote in message
news:42******** *************** @un-2park-reader-02.sydney.pipen etworks.com.au. .. "Howard" <al*****@hotmai l.com> wrote in message news:CN******** ***********@bgt nsc04-news.ops.worldn et.att.net "Karl Heinz Buchegger" <kb******@gasca d.at> wrote in message > So in short: There is no array of pointers, just a pointer to an dynamically allocated array.
D'oh! I got confused. Somehow, I was thinking that he'd allocated an array
of pointers. But, that would have been:
candybar** snack = new (candybar*)[10];
My bad. I'll go slink off into a corner and hide my face now.
-Howard
On Fri, 01 Apr 2005 22:27:10 -0800, Steven Taylor
<ne******@super jacent.net> wrote:
Besides, what is mentioned, you have to use:
delete[] , when deallocating what was allocated using new objects[]
Regards
Benny Andersen This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: berthelot samuel |
last post by:
Hi everyone,
This really is a tricky one ! (at least for me:). Actually I haven't
found any solution to this problem anywhere...
So I'll try to be as clear as possible in my explanations. First, I
have the following structure:
typedef struct _object3D {
float coord;
float r, g, b;
} object3D;
|
by: Mannequin* |
last post by:
Hi all,
I'm working on a quick program to bring the Bible into memory from a
text file. Anyway, I have three questions to ask.
First, is my implementation of malloc () correct in the program to
follow?
Second, have I correctly passed the structure's pointer to the
functions in this program?
|
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 static; if the input
file contained more than entries, tough.
This time I want to do it right - use a dynamic array that increases in
size with each word read from the file. A few test programs that make use
of **List and realloc( List, blah...
|
by: xinsir |
last post by:
dynamic array as a byref parameter by used in function and
have a Marshal error ,what is the matter?thanks
source like as this .
------------------------------------------------------
Declare Function finit Lib "DllCap.dll" _
(ByRef rdAcnt As ACNTINF2) As Integer
<StructLayout(LayoutKind.Sequential)> Structure ACNTINF
<MarshalAs(UnmanagedType.ByValTStr, sizeconst:=16)> Dim
|
by: vinod.bhavnani |
last post by:
Hello all,
I need desperate help
Here is the problem:
My problem today is with multidimensional arrays.
Lets say i have an array A this is a 4 dimensional
static array.
| |
by: Nutkin |
last post by:
Basicly i have to make a program that calculates the distance between x
and y points in 2d space.
the code basicly goes like this
1. User says how many points they have (max of 10)
2. User enters points
3. Using sqrt( (x2-x1)^2 + (y2-y1)^2) ) It calculates the distance
|
by: gunimpi |
last post by:
http://www.vbforums.com/showthread.php?p=2745431#post2745431
********************************************************
VB6 OR VBA & Webbrowser DOM Tiny $50 Mini Project Programmer help
wanted
********************************************************
For this teeny job, please refer to:
http://feeds.reddit.com/feed/8fu/?o=25
|
by: Opteron64 |
last post by:
Hi,
I'm trying to create and initialise a dynamic array within a nested structure. The structure is defined as followed:
(C++ code)
typedef unsigned char uchar;
typedef unsigned int uint;
struct Results_list {
|
by: Gurur |
last post by:
Hi all,
I have a doubt.
If I have 2 structures and one is parent of other , ie the child
structure is present in the parent one . And if the child structure is
declared as dynamic array in the parent , will it be possible to pass
the parent structure thru network using sockets onto other application
running on different system provided the API is known to both the
sender and the receiver.
|
by: dreiko466 |
last post by:
(sorry about my english...)
I am a newbie in C (3 month expierience)
I have wrote a simple test programm in VS2005, what i do wrong?Please...
In this programm i create a double linked list.Then pass its first block pointer
inside the structure Array to Array ->first and the last block pointer inside the structure Array to Array ->last.So i can manipulate the double linked list as a dynamic array. The cells of this dynamic array are...
|
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...
| |
by: Hystou |
last post by:
Overview:
Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
|
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...
|
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...
|
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();...
|
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...
|
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
| |
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: 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...
| |