| | |
String Swap Not Working
![]() |
•
•
Join Date: Jul 2009
Posts: 9
Reputation:
Solved Threads: 1
Hi, this is the code that I have to swap two strings-
output- (new,word)
Why is the swap function not swapping the strings once the control comes out of swap? I am passing it using pointers (by reference).
C Syntax (Toggle Plain Text)
void swap(char *,char *); main() { char *x="new"; char *y="word"; char *t; swap(x,y); printf("(%s,%s)",x,y); } void swap(char *x,char *y) { char *t; t=x; x=y; y=x; }
output- (new,word)
Why is the swap function not swapping the strings once the control comes out of swap? I am passing it using pointers (by reference).
Because you're only swapping within the scope of the function. Instead you need to pass the address of the pointers, not the memory referenced by those pointers!
Despite that, line 21 was wrong!
Despite that, line 21 was wrong!
C Syntax (Toggle Plain Text)
void swap(char *,char *); main() { char *x="new"; char *y="word"; swap( &x, &y ); printf("(%s,%s)",x,y); } void swap( char **x, char **y) { char *t; t = *x; *x = *y; *y = t; }
Last edited by wildgoose; Jul 11th, 2009 at 7:37 pm.
"One of the methods used by statists to destroy capitalism consists in establishing controls that tie a given industry hand and foot, making it unable to solve its problems, then declaring that freedom has failed and stronger controls are necessary." --Ayn Rand
rcbhat,
Declaration of your code is pointer to chars.
'x' points to the first char of "new" which is an
array of constant chars in C++. A special rule in C++ allows the
assignment of the address of a string literal (array of const char) to
a pointer to modifiable char(s). Attempting to modify any const
object in C++, including string literals, produces undefined behavior.
If you are talking about C, not C++, the type of the string literal is
array of chars and NOT array of constant chars. Attempting to modify
a string literal in C produces undefined behavior not because they are const qualified chars, but because the C standard specifically states that it is undefined behavior.
http://c-faq.com/charstring/index.html
http://www.parashift.com/c++-faq-lite/
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
OP has another thread with different question for pointer to characters. - http://www.daniweb.com/forums/thread203375.html
Array of chars and pointer to chars is not same thing.Declaration of your code is pointer to chars.
C++ Syntax (Toggle Plain Text)
char *x="new"; char *y="world"; ...
array of constant chars in C++. A special rule in C++ allows the
assignment of the address of a string literal (array of const char) to
a pointer to modifiable char(s). Attempting to modify any const
object in C++, including string literals, produces undefined behavior.
If you are talking about C, not C++, the type of the string literal is
array of chars and NOT array of constant chars. Attempting to modify
a string literal in C produces undefined behavior not because they are const qualified chars, but because the C standard specifically states that it is undefined behavior.
http://c-faq.com/charstring/index.html
http://www.parashift.com/c++-faq-lite/
http://www.club.cc.cmu.edu/~ajo/docs/FAQ-acllc.html
OP has another thread with different question for pointer to characters. - http://www.daniweb.com/forums/thread203375.html
Failure is not fatal, but failure to change might be. - John Wooden
•
•
Join Date: Jul 2009
Posts: 9
Reputation:
Solved Threads: 1
•
•
•
•
Attempting to modify a string literal in C produces undefined behavior not because they are const qualified chars, but because the C standard specifically states that it is undefined behavior.
I realized that this cannot be accomplished using pass by values unless I am able to work with the actual pointers to the pointers to the chars (i.e. the pointers to the first elements of the string literals)
So, correct me if you think I may be wrong, but your reply is out of context for the question.
•
•
•
•
So, correct me if you think I may be wrong, but your reply is out of context for the question.
because your original question and code made it appear that you were operating on a misconception about string literals. even if you did not actually have this misconception, it's a common problem and an unclear question could easily confuse others.
since these threads here will be available for a long time, his clarification is as much for future reference and is entirely appropriate.
•
•
Join Date: Jul 2009
Posts: 5
Reputation:
Solved Threads: 0
I think there's only one reason why your code will never work as you expected: you declare read-only strings. Although you didn't declare it with the const keyword, declaring string that way makes your string variable untouchable.
Here are my suggestions:
You either write your code this way:
1.... char szStr1[] = "Hello";
2.... char szStr2[] = "About";
Take note that your strings have the same length. Although it should not be necessary, you have to make sure your string arrays' length can accomodate the length of the longer one.
3.... void strSwap(char* str1, char* str2)
{
char szTemp[1024];
strcpy(szTemp, str1);
strcpy(str1, str2);
strcpy(str2, szTemp);
}
...or write your function this way:
1.... void strSwap(char** ppStr1, char** ppStr2)
{
char * szTemp;
int cch1, cch2;
cch1 = strlen(*ppStr1);
cch2 = strlen(*ppStr2);
szTemp = (char*)malloc(cch1+1);
strcpy(szTemp, *ppStr1);
*ppStr1 = (char*)malloc(cch2+1);
strcpy(*ppStr1, *ppStr2);
*ppStr2 = szTemp;
}
In the method, you have to declare you strings like this:
char * szStr1 = "Help";
char * szStr2 = "Anonymous";
strtSwap(&szStr1, &szStr2);
...
// use your szStr1 and szStr2
...
free(szStr1);
free(szStr2);
Well, the second method I think is costly. I just hope I can help you solve, or at least give a hint in solving your problem.
Here are my suggestions:
You either write your code this way:
1.... char szStr1[] = "Hello";
2.... char szStr2[] = "About";
Take note that your strings have the same length. Although it should not be necessary, you have to make sure your string arrays' length can accomodate the length of the longer one.
3.... void strSwap(char* str1, char* str2)
{
char szTemp[1024];
strcpy(szTemp, str1);
strcpy(str1, str2);
strcpy(str2, szTemp);
}
...or write your function this way:
1.... void strSwap(char** ppStr1, char** ppStr2)
{
char * szTemp;
int cch1, cch2;
cch1 = strlen(*ppStr1);
cch2 = strlen(*ppStr2);
szTemp = (char*)malloc(cch1+1);
strcpy(szTemp, *ppStr1);
*ppStr1 = (char*)malloc(cch2+1);
strcpy(*ppStr1, *ppStr2);
*ppStr2 = szTemp;
}
In the method, you have to declare you strings like this:
char * szStr1 = "Help";
char * szStr2 = "Anonymous";
strtSwap(&szStr1, &szStr2);
...
// use your szStr1 and szStr2
...
free(szStr1);
free(szStr2);
Well, the second method I think is costly. I just hope I can help you solve, or at least give a hint in solving your problem.
![]() |
Similar Threads
- C++ String Swap (C++)
- command line string swap (C)
Other Threads in the C Forum
- Previous Thread: Printing Question
- Next Thread: Postfix operation
| Thread Tools | Search this Thread |
#include * ansi array arrays asterisks binarysearch calculate centimeter changingto char character convert copyanyfile copyimagefile copypdffile creafecopyofanytypeoffileinc createprocess() database dynamic execv fflush fgets file floatingpointvalidation fork forloop function getlogicaldrivestrin givemetehcodez grade gtkwinlinux histogram homework i/o ide inches include infiniteloop input interest intmain() iso keyboard km license linked linkedlist linux list looping lowest matrix meter microsoft mysql number oddnumber open opendocumentformat openwebfoundation pdf pointer posix power probleminc process program programming pyramidusingturboccodes radix read recursion recv recvblocked research reversing scheduling segmentationfault send sequential single socket socketprogramming stack standard strchr string suggestions systemcall test threads turboc unix urboc user variable whythiscodecausesegmentationfault win32api windowsapi






