How to swap string in C? -


i trying make function in c swap 2 string variables went wrong , program crashes.

please have @ code , tell me made mistake:

#include <string.h>  void strswap(char name1[], char name2[])    // swap 2 strings {     int lengthname1, lengthname2;     lengthname1 = strlen(name1);     lengthname2 = strlen(name2);     char temporaryname1[100];     char temporaryname2[100];     int x;     int y;     // till declaration     (int x = 0; x < lengthname1; lengthname1++) {         temporaryname1[x] = name1[x];         name1[x] = ' ';     }     // copying value of name1 in temporaryname1     (int y = 0; y < lengthname2; lengthname2++) {         temporaryname2[x] = name2[x];         name2[x] = ' ';     }     // copying value of name2 in temporaryname2     (int x = 0; x < lengthname1; lengthname1++) {         name1[x] = temporaryname2[x];     }     (int y = 0; y < lengthname2; lengthname2++) {         name2[x] = temporaryname1[x];     } }   #include <stdio.h> int main() {     char name[] = "hello";     char name2[] = "hi";     printf("before swapping: %s %s\n", name, name2);     strswap(name, name2);     printf("after swapping: %s %s\n", name, name2); } 

edit:- have corrected program , working properly. header file going work other modules. thank , @micheal

there many issues:

first issue

the x variable not initialized:

    int x; int y;  // first declaration of x      // till declaration     for(int x=0;x<lengthname1;lengthname1++)     {//  ^ second declaration of x , local loop         temporaryname1[x]=name1[x];         name1[x]=' ';     }    // if use x here it's first x has never been initialized 

second issue

this:

for (x = 0; x<lengthname1; lengthname1++) 

should be:

for (x = 0; x<lengthname1 + 1; x++) 

why lengthname1 + 1 ? because need copy nul char terminates string.

there similar problems in other for loops well.

for example here use y loop variable, in loop use x:

for (int y = 0; y<lengthname2 + 1; lengthname2++) {   name2[x] = temporaryname1[x]; 

third issue

in main declare this:

char name[] = "hello"; char name2[] = "hi"; 

that same as

char name[6] = "hello";  // 5 chars "hello" + 1 char terminating nul char name2[3] = "hi";    // 2 chars "hi" + 1 char terminating nul 

now if strswap correct, trying stuff 6 bytes name array ("hello") 3 bytes array name2, there not enough space in name2 array. undefined behaviour.

and last not least:

this useless:

name1[x] = ' '; 

and finally

you should ask why need 2 temporary strings (temporaryname1 , temporaryname2) in strswap() - 1 enough.


Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - jQuery UI Splitter/Resizable for unlimited amount of columns -

javascript - IE9 error '$'is not defined -