0

I have a struct in C++

typedef struct DIFColor
{
    uint8_t r;
    uint8_t g;
    uint8_t b;


} DIFColor;

And am trying to initialize it like this:

DIFColor d = new DIFColor();

d.r = r;
d.g = g;
d.b = b;

But the compiler complains about not being able to convert a pointer to a regular variable. What pointer? From this question I thought you could simply create a new struct without having to deal with pointers and dynamic memory allocation with new. Does it have something to do with the fact that I am initializing the struct like one would in C, instead of using a constructor?

error: conversion from 'DIFColor*' to non-scalar type 'DIFColor' requested
Community
  • 1
  • 1
Igor
  • 548
  • 3
  • 7
  • 24
  • 1
    There are many questions trying to do this. Why don't people read tutorials before using the language? – Neil Kirk Jul 30 '14 at 13:47

5 Answers5

6

Try:

DIFColor d = { r, g, b };
Brandon Kohn
  • 1,612
  • 8
  • 18
3

The operator new will return a pointer to your struct. If you want to declare the object on the heap

DIFColor* d = new DIFColor;
d->r = r;
d->g = g;
d->b = b;

Or to declare it on the stack don't use new.

DIFColor d;
d.r = r;
d.g = g;
d.b = b;
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
2

You should not use dynamic allocation without reason, and there is no reason in your code, so remove new:

DIFColor d = new DIFColor();

replace with

DIFColor d;
Wojtek Surowka
  • 20,535
  • 4
  • 44
  • 51
1

The new keyword in

DIFColor d = new DIFColor();

creates a pointer. You should either write

DIFColor d = {r,g,b}; // allocate on stack

or

DIFColor * d = new DIFColor(); // make a pointer
dirkster
  • 522
  • 2
  • 5
1

new operator returns a pointer.

So, correct syntax would be:

DIFColor* d = new DIFColor();
Tomas
  • 2,170
  • 10
  • 14