structs and c style strings

Im trying to learn how to use structs now and i can't seem to figure it out, Im having problems using a c style string or char array in my struct and there are absolutely zero online resources i can find to help me on the topic.
why doesnt this work:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>


using namespace std;

struct supercar{
char make[1][15] = {};
char model[1][10] = {};
};


int main()
{
supercar one;

one.make[1][15] = {"Lamborghini"};
one.model[1][10] = {"Gallardo"};

for (int i = 0; i < 11; i++)
	{	
		cout << one.make[i] << endl;
		cout << one.model[i] << endl;	
	}




}

It keeps saying in converting from const char* to char but i never set a const char* i dont even know what that means


but this works without the use of my struct.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 #include <iostream>

using namespace std;

int main () {

char make[1][15] = {"Lamborghini "};
char model[1][10] = {"Gallardo"};

for (int i = 0; i < 1; i++)
	{	
		cout << make[i];
		cout << model[i] << endl;	



return 0;
}
1
2
one.make[1][15] = {"Lamborghini"};
one.model[1][10] = {"Gallardo"};


These are assignments, not initialization statements. You are trying to assign pointer to const char to a char element, which is incorrect.

The best fix is to use strcpy (include <cstring>) :
1
2
strcpy(one.make[0], "Lamborghini");
strcpy(one.model[0], "Gallardo");


Now the code works just sweet.
Last edited on
for (int i = 0; i < 11; i++) // The first example

Why is this not the same as :

for (int i = 0; i < 1; i++) // The second example

Which one is right?

???
Forget the loops. 1 and 11 are not equal, but I suspect a typo or something here. I have no idea what you are doing with those.

but here are some things I see.

struct supercar{
char make[15];
char model[10];
};

this looks like what you wanted to express. the 1 is understood.
char make [1][15] is not exactly the same as
char make[15] but it is "logically" the same and more correct.

you only want to do a 2-d array if you actually have 2 dimensions; here, you might like an array of strings, which would look like

char aos[10][100] which is 10 strings, 100 long each. Making it 1 long and 15 wide... is pretty much the same as just having it, and it being 15 wide. Does that make sense?

with the above struct, you should now be able to do this:

main()
{
supercar one;
strcpy(one.make "carmake");
strcpy(one.model, "carmodel");
cout << one.make <<endl << one.model << endl;

// or you can even get really fancy

supercar several[10];
for(j = 0; j < 10; j++)
{
///read 10 cars in from user or something.

}


}

Topic archived. No new replies allowed.