1

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;
  }
}
3
  • 2
    Please edit the question to fix the formatting. For future posts, please check the preview before posting. Commented Apr 26, 2016 at 22:30
  • 3
    If it's c++, why don't you just use std::string to represent strings (and std::swap to swap them)? Commented Apr 26, 2016 at 22:31
  • Besides: "I have a char array that holds another 6 char arrays" No you don't. You need to read your learning material more carefully; and if it actually tells you to use C arrays for string manipulation, you should get a better book. Commented Apr 26, 2016 at 22:32

2 Answers 2

5

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?

Sign up to request clarification or add additional context in comments.

1 Comment

Yeah, you are right I taking a course of c++ and that's why I am doing it that way. BTW thanks for help .
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.