[英]How to swap string in C?
我試圖在C中創建一個函數,它將交換兩個字符串變量,但出現問題,程序崩潰。
請看看我的代碼並告訴我我在哪里犯了錯誤:
#include <string.h>
void strswap(char name1[], char name2[]) // to swap two strings
{
int lengthname1, lengthname2;
lengthname1 = strlen(name1);
lengthname2 = strlen(name2);
char temporaryname1[100];
char temporaryname2[100];
int x;
int y;
// till just the declaration
for (int x = 0; x < lengthname1; lengthname1++) {
temporaryname1[x] = name1[x];
name1[x] = ' ';
}
// copying the value of name1 in temporaryname1
for (int y = 0; y < lengthname2; lengthname2++) {
temporaryname2[x] = name2[x];
name2[x] = ' ';
}
// copying the value of name2 in temporaryname2
for (int x = 0; x < lengthname1; lengthname1++) {
name1[x] = temporaryname2[x];
}
for (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);
}
編輯: - 我已糾正該程序,它正常工作。 不久我的頭文件將與其他一些模塊一起使用。 謝謝大家的幫助,特別是@Micheal
有很多問題:
x
變量未初始化:
int x; int y; // first declaration of x
// till just the declaration
for(int x=0;x<lengthname1;lengthname1++)
{// ^ second declaration of x , local to the loop
temporaryname1[x]=name1[x];
name1[x]=' ';
}
// if you use x here it's the first x that has never been initialized
這個:
for (x = 0; x<lengthname1; lengthname1++)
應該:
for (x = 0; x<lengthname1 + 1; x++)
為什么lengthname1 + 1
? 因為您需要復制終止字符串的NUL字符。
還有你的其他類似問題for
循環,以及。
例如,在這里使用y
作為循環變量,但在循環中使用x
:
for (int y = 0; y<lengthname2 + 1; lengthname2++)
{
name2[x] = temporaryname1[x];
main
你宣布:
char name[] = "hello";
char name2[] = "hi";
這實際上是一樣的
char name[6] = "hello"; // 5 chars for "hello" + 1 char for the terminating NUL
char name2[3] = "hi"; // 2 chars for "hi" + 1 char for the terminating NUL
現在即使你的strswap
是正確的,你也試圖將name
數組中的6個字節(“hello”)填充到3個字節的數組name2
, name2
數組中沒有足夠的空間。 這是未定義的行為。
這根本沒用:
name1[x] = ' ';
您應該問自己為什么在strswap()
需要兩個臨時字符串( temporaryname1
和temporaryname2
strswap()
- 一個就足夠了。
void strswap(char ** name1, char ** name2)
{
char * name1_1 = malloc(strlen(*name2) + 1);
char * name2_1 = malloc(strlen(*name1) + 1);
strncpy(name1_1, *name2, strlen(*name2) + 1);
strncpy(name2_1, *name1, strlen(*name1) + 1);
*name1 = name1_1;
*name2 = name2_1;
}
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);
return 0;
}
實際上以下是交換兩個字符串最安全的方法。 在您的情況下,您靜態使用大小為100的字符串,這是不好的,並且在所有情況下都可以使用。 此外,您嘗試使用''而不是'\\ 0'來標記字符串的結尾。 String API使用'\\ 0'表示字符串已結束。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.