this program is meant to take two strings and call a function that copies string 1 into string2, and vice versa, while fulfilling the following criteria:
- Uses pointers
- Uses only while loops
- does not use strcpy();
This is what I have, but nothing shows up. How can I fix this?
#include<stdio.h>
void string_copier(char *a, char *b);
int main(){
char string1[100], string2[100];
/*read strings*/
printf("Enter a string less than 100 characters.\n");
gets(string1);
//scanf("%s", &string1);
printf("Enter another string less than 100 characters.\n");
gets(string2);
//scanf("%s", &string2);
/*call function*/
string_copier(string1, string2);
/*print new strings*/
printf("%s\n", string1);
printf("%s\n", string2);
}
void string_copier(char *a, char *b){
int i = 0;
char *swap;
/*assign string a to swap variable*/
while(*(a + i) != '\0'){
*(swap + i) = *(a + i);
i++;
}
*(swap + i) = '\0';
/*redefine i to use in next while loop*/
i = 0;
/*assign b to a*/
while(*(b + i) != '\0'){
*(a + i) = *(b + i);
i++;
}
*(a + i) = '\0';
i = 0;
/*assign swap to b*/
while(*(swap + i) != '\0'){
*(b + i) = *(swap + i);
i++;
}
*(b + i) = '\0';
}
Thank you.
char *swap;
is just a pointer... you can't store any data in it....swap
is just an uninitialized pointer so it doesn't point to valid memory. One thing you can do isswap = malloc(100);
but you can also just make it an array likechar swap[100];
char swap;
and then swap the characters one by one instead "copying" the whole string first...gets
, find a better professor. Read stackoverflow.com/questions/1694036/… or any link about gets you can find