0

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};
	
}
3
Contributors
7
Replies
10
Views
6 Years
Discussion Span
Last Post by garu525
0
#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};

}

Edited by Narue: Added code tags

0

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,

0
#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};

 }

Edited by Narue: Added code tags

0

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;
}
0

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!

0

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.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.