You have the right idea, i.e using a hold variable of the same type to contain intermediate result while transferring the two array rows, but a couple of things to address first:
As mentioned in the comments, hold
does not need to be an array. That simple fix will allow your function to be called in a loop. This is an example with minor edits to illustrate your function, and how it would be called:
int main(void)
{
char names[][31] = {{"THIS STRING IS UPPER CASE"},{"this string is lower case"}};
for(int i = 0;i<sizeof(names[0])/sizeof(names[0][0]);i++)
{
swap(names, i, i);//must be called in loop to complete swap
}
}
//swaps one char per call and returns
void swap(char name[][31],int i,int j)
{
char hold;
hold=name[0][i];
name[0][i]=name[1][j];
name[1][j]=hold;
}
Suggestions on style
For efficiency, readability and maintainability it is often better to move as much work related to a function into the function itself. In this case, rather then looping on swap
31 times, by making a change to the argument list, and moving the looping into the function, it can be called once, and still provide the desired result.
The following is an example of your method, but adapted to do all work internally. Note changes to the argument list.
//adaptation of original method with internal looping
void swap1(char **str)
{
int len = strlen(str[0]);//same len, test one.
char hold = 0;
for(int i = 0;i < len;i++)
{
hold = str[0][i];
str[0][i] = str[1][i];
str[1][i] = hold;
}
}
And, per suggestion in comments, if char arrayare each
\0` terminated, they qualify as a pair of C strings, allowing use of the string function strcpy() to simplify by removing need to loop.
//using strcpy() to simplify swap
void swap2(char **str)
{
int len = strlen(str[0]);//same len, test one.
char hold[len+1];
strcpy(hold, str[0]);
strcpy(str[0], str[1]);
strcpy(str[1], hold);
}
Finally, the following shows the new calling method, used for both variations:
void swap1(char **str);//char by char
void swap2(char **str);//use strcpy()
int main(void)
{
//char name[2][80] = {{"name1IsLongerThan2"}, {"Name2IsShorter"}};
char *name1 = "name1IsLongerThan2";
char *name2 = "Name2IsShorter ";//Note for this example,
//both strings must be same length
char *name[] = {name1, name2};
swap1(name);
printf("name 1: %s\nname 2: %s\n", name[0], name[1]);
swap2(name);
printf("name 1: %s\nname 2: %s\n", name[0], name[1]);
return 0;
}