Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void swap(char* s1, char* s2)
{
char* temp = s1;
s1 = s2;
s2 = temp;
}
int main()
{
char *str_array[4];
char buffer[128];
int i;
for (i = 0; i < 4; i++)
{
printf("Enter string %d: ", i + 1);
scanf("%s", buffer);
int length = strlen(buffer); //get the length of the inputed string
++length; //add a space for the NULL charactor at the end
//allocate space at i in the str_array for the word
str_array[i] = malloc(length * sizeof(char));
//copy the word into the array
strcpy(str_array[i], buffer);
}
//swap first word and second word
swap(&str_array[0], &str_array[1]);
//display words
for (i = 0; i < 4; i++)
printf("%s\n", str_array[i]);
//free allocated memory
for (i = 0; i < 4; i++)
free(str_array[i]);
return 0;
}
If I enter: car boat plane train I want to to swap car and boat. So it would then display boat car plane train.
On the line where I call the swap function i get:
Code:
warning: passing arg 1 of `swap' from incompatible pointer type
What is the correct way to go about swapping strings in an array? Thank you for any help.