I'm having an error "a value of type "double" cannot be used to initialize an entity of type "double *"

Any tips? Thanks!

#include <iostream>
#include <string>
using namespace std;

struct sample {
	string name;
	double *num;
	unsigned elements;
};


int main () {
	sample x  = {"Dude", {1, 2, 3, -5}, 4};
	
}
#include <iostream>
#include <string>
using namespace std;

struct sample {
	string name;
	double num[4];
	unsigned elements;
};


int main () {
	sample x  = {"Dude", {1., 2., 3., -5.}, 4};

}

thank you, but I was instructed to only use dynamic arrays in a struct so i don't want to limit it to just 4 elements, it coulb be 2 or 1000. so the only thing i'm thinking is by a pointer. any tips?

best regards,

#include <iostream>
 #include <string>
 using namespace std;

 struct sample {
 string name;
 double *num;
 unsigned elements;
 };


 int main () 
 {
	 double numb[]={1., 2., 3., -5.};
 sample x = {"Dude",numb , 4};

 }

A pointer is not an array, it only plays one on television. You have to allocate memory to the pointer and then assign values, which for the purpose of this post we'll say you cannot do in a structure initialization list:

#include <iostream>
#include <string>

using namespace std;

struct sample {
    string name;
    double *num;
    unsigned elements;
};

int main ()
{
    sample x  = {"Dude", 0, 4};
    double init[] = {1, 2, 3, -5};
    
    x.num = new double[x.elements];
    
    for (int i = 0; i < x.elements; i++)
        x.num[i] = init[i];
    
    cout << x.name << '[' << x.elements << "]:\n";
    
    for (int i = 0; i < x.elements; i++)
        cout << '(' << x.num[i] << ")\n";
        
    delete[] x.num;
}

Thanks fr the quick response guys, but I forgot to mention that this line is preset by my instructor:

sample x  = {"Dude", {1., 2., 3., -5.}, 4};

So I can't separate the {1., 2., 3., -5.} from the line. Any tips? Thanks again!

I forgot to mention that this line is preset by my instructor

Then one of the following is true:

  • You misunderstood the requirements of the program.
  • You're expected to use a non-standard compiler extension.
  • Your instructor is setting you up for failure by asking for the impossible.

I'd wager it's the first one, maybe you should verify what your instructor expects. Note that I'm assuming you aren't allowed to use a C++11 solution.

Thanks! I will check on this.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.