C++ pointer question

  • Thread starter Thread starter Deleted member 61728
  • Start date Start date

Deleted member 61728

Deleted member 61728

Hi ive been playing around with some pointers and am wondering how do I make pointer *mycar point to the second object of type car after populating the first object with those two values?

struct car{

int engine_size;
int number_doors;

};


car *mycar = NULL;


mycar = new car[2];


mycar->engine_size = 10;
mycar->number_doors = 20;


cout<<mycar->engine_size<<endl;;
cout<<mycar->number_doors<<endl;


delete mycar;





thanks
 
(mycar + 1)->engine_size = 5;

or

mycar[1].engine_size = 5;

Both amount to offseting the memory address (pointer) by 1 times the number of bytes that a car struct occupies. You could also use 0 when accessing the first one to make the code look consistent. "cars" might be a more appropriate name given it is an array, so you'd access them like cars[0], cars[1], etc.

"delete mycar" would only delete the first car in the array. Use "delete[] mycar" to delete all of them .
 
Last edited:
Your pointer math in the first one is ****.

mycar + 1 will be the base address of mycar + 1, you'd need mycar + sizeof(car);
 
You could also use 0 when accessing the first one to make the code look consistent. "cars" might be a more appropriate name given it is an array, so you'd access them like cars[0], cars[1], etc.

"delete mycar" would only delete the first car in the array. Use "delete[] mycar" to delete all of them .

This is good advice - I've always felt that using array indices is far nicer than pointer arithmetic (although I beleive this is what it will do internally).

Pointer arithmetic is always easier to get wrong as Dfhaii pointed out!
 
Isn't the point of pointer arithmetic that (mycar + n) is implicitly (mycar + n*sizeof(car)) ?

Writing (mycar + sizeof(car)) would offset you 8*8 = 64 bytes in this case, no?
 
The end result of writing (mycar + sizeof(car)) would be a pointer to the base address plus 64 bytes in this case, which is obviously not what is wanted since each struct is 8 bytes.

Which is why Dfhaii is wrong and I was right in the first post :/
 
Last edited:
Crikey, apologies. It is so seldom that I have to use pointer arithmetic that I never noticed my misapprehension!
 
Back
Top Bottom