Reputation: 97
I am writing an exchange program and I have a char array that holds another 6 char arrays. The program works fine except for one thing: when I try to print the arrays' values, it prints only the first letter.
Maybe the code isn't right, but I didn't find another way to make this exchange. Actually I think the problem is in pointers that point to that arrays, but again I am not sure.
Here is the code:
#include <iostream>
#include <string>
#include <fstream>
#include <stdlib.h>
using namespace std;
int main(int argc, char* argv[])
{
cout<<"EXCHANGE POKEMON:"<<endl;
char a[100]="PIKACHU", b[100]="CHARMELEON", c[100]="GEODUDE", d[100]="GYARADOS", e[100]="BUTTERFREE", f[100]="MANKEY", tmp[100];
char t[6] = {*a,*b,*c,*d,*e,*f};
while(1)
{
for(int i = 0; i < 6; i++)
{
cout << i << ") " << t[i] <<endl;
}
cout<<endl<<"Choose a pokemon:";
int x, y;
cin>>x;
if(x == -1)
{
exit(0);
}
cout << "Choose a pokemon to exchange with:";
cin>>y;
*tmp = t[x];
t[x] = t[y];
t[y] = *tmp;
}
}
Upvotes: 1
Views: 21065
Reputation: 98348
With this line:
char t[6];
you are not creating an array of arrays of char. You are creating a simple array of chars. So it is no surprise that every element is a single character.
You probably want:
char *t[6] = {a, b, c, d, e, f};
Note that the *a
is actually equivalent to a[0]
!
Then the tmp
array is used wrong: in C you copy strings with strcpy()
, not with the assignment operator. Or alternatively you hold a pointer to the original string.
But you are using C++, so why not just use std::string
? Maybe you are just learning arrays and want to do it the hard way?
Upvotes: 5
Reputation: 39164
You defined t
as an array of char, initialized dereferencing the address of the arrays defined before. That is equivalent to obtaining their first element.
*a is equivalent to a[0]
What you are looking for is an array of char pointer instead:
char *t[6] = {a,b,c,d,e,f};
Upvotes: 2