Reputation: 369
I have a 2D character array, I want to swap two rows of this array. I can think of this function.
char str[5][5];
swap(str[i],str[j]);
void swap(char * p, char *q) {
char *temp;
temp = p;
p = q;
q = temp;
}
This function does not work. I also came up with this,
char ** temp1;
char ** temp2;
temp1 = &str[i];
temp2 = &str[j];
*temp1 = str[j];
*temp2 = str[i];
This does not work either, please suggest me a proper way to do this task.
Upvotes: 0
Views: 3316
Reputation: 310990
Try the following approach
#include <stdio.h>
#include <string.h>
void swap( char *s1, char *s2, size_t n )
{
char t[n];
strcpy( t, s1 );
strcpy( s1, s2 );
strcpy( s2, t );
}
#define N 5
int main(void)
{
char s[N][N] =
{
"Cat",
"Dog",
"Cow",
"Bird",
"Goat"
};
for ( size_t i = 0; i < N; i++ ) puts( s[i] );
puts( "" );
swap( s[0], s[3], N );
for ( size_t i = 0; i < N; i++ ) puts( s[i] );
return 0;
}
The program output is
Cat
Dog
Cow
Bird
Goat
Bird
Dog
Cow
Cat
Goat
Take into account that you can use also standard function strncpy
instead of strcpy
.
The other approach is to use standard function memcpy
that to copy exactly N characters.
Upvotes: 1
Reputation: 726599
Since this is a contiguous 2D array, not an array of pointers, one should use memcpy
to copy five-element subarrays, like this:
void swap(char *p, char *q) {
char temp[5];
memcpy(temp, p, sizeof(temp));
memcpy(p, q, sizeof(temp));
memcpy(q, temp, sizeof(temp));
}
The idea is to make an array buffer sufficient to hold one "row", copy the first row into it, and then do the swap the usual way (i.e. with an assignment of a temporary variable).
Upvotes: 0
Reputation: 7320
Use a loop to swap every elements of the two rows :
void swapRows(char* row1, char* row2, size_t rowlen)
{
for (size_t i=0; i<rowlen; ++i)
{
char tmp = row1[i];
row1[i] = row2[i];
row2[i] = tmp;
}
}
Here we have a function that takes a pointer to two rows of your array, the length of a row, and that runs a very simple loop to swap every elements of those rows. Here is how you would use it :
int main()
{
char str[2][2] = {{'1','2'},{'3','4'}};
swapRows(&str[0][0], &str[1][0], 2);
// str now contains {'3','4'},{'2','1'}
}
What you seem to have tried is to swap the pointers to the rows instead of physically moving the content of the rows. That can't work. Pointers only allow you to find your data, but moving them around doesn't actually modify that data. Now, if you had a char**
array this idea would work, but in the case of a contiguous 2D char[][]
array you have to move things physically.
Upvotes: 0
Reputation: 651
void swap( char * ary, int idx1, int idx2, int rowlen )
{
for ( int x=0; x<rowlen; x++ )
{
temp = ary[idx1][x];
ary[idx1][x] = ary[idx2][x];
ary[idx2][x] = temp;
}
}
#define ROWLEN 5
void main( void )
{
char str[5][ROWLEN];
swap( str, 2, 4, ROWLEN ); // swap rows 2 and 4
}
I didn't compile this so there might be syntax errors, but this should convey the idea.
Upvotes: 0