0

Hello everybody. I want to make a piece of code that its main job will be to swap rows in a 2d char array. I wrote the following piece of code:

#include <iostream>

using namespace std;

void swap(char *s1, char *s2);

int main() {

 char arr[3][10];
  cout << "give me 3 names\n";
  for (int i = 0; i < 3; i++)
   cin >> arr[i];

   cout << "array before:\n";
  for (int i = 0; i < 3; i++)
   cout << arr[i];

  swap(arr[0], arr[2]);

  cout << "array after:\n";
  for (int i = 0; i < 3; i++)
   cout << arr[i];

   return 0;
}

void swap(char *s1, char *s2) {

 char *temp;
 temp = s1;
 s1 = s2;
 s2 = temp;
}

and it didn't work
then i changed the swap function into the following:

void swap(char *s1, char *s2) {

 char *temp;
 strcpy(temp, s1);
 strcpy(s1, s2);
 strcpy(s2, temp);
}

and it worked. Could anyone please enlighten me why the first piece of code didn't work? I have something on my mind but i'm not pretty sure... Thank you in advance for spending your time with me..

2
Contributors
1
Reply
3
Views
6 Years
Discussion Span
Last Post by WaltP
0

Because you cannot access a character array as if it is one thing. You wouldn't expect to do this, would you?

void swap(int *s1, int *s2) {

 int *temp;
 temp = s1;
 s1 = s2;
 s2 = temp;
}

A 'string' is just a character array that has \0 in it..

This topic has been dead for over six months. 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.