我试图在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);
}
Run Code Online (Sandbox Code Playgroud)
编辑: - 我已纠正该程序,它正常工作.不久我的头文件将与其他一些模块一起使用.谢谢大家的帮助,特别是@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
Run Code Online (Sandbox Code Playgroud)
这个:
for (x = 0; x<lengthname1; lengthname1++)
Run Code Online (Sandbox Code Playgroud)
应该:
for (x = 0; x<lengthname1 + 1; x++)
Run Code Online (Sandbox Code Playgroud)
为什么lengthname1 + 1?因为您需要复制终止字符串的NUL字符.
您的其他for循环也存在类似的问题.
例如,您在此处使用y循环变量,但在循环中使用x:
for (int y = 0; y<lengthname2 + 1; lengthname2++)
{
name2[x] = temporaryname1[x];
Run Code Online (Sandbox Code Playgroud)
在main你声明这个:
char name[] = "hello";
char name2[] = "hi";
Run Code Online (Sandbox Code Playgroud)
这实际上是一样的
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
Run Code Online (Sandbox Code Playgroud)
现在,即使你strswap是正确的,你也试图将name数组中的6个字节("hello")填充到3个字节的数组中name2,数组中没有足够的空间name2.这是未定义的行为.
这根本没用:
name1[x] = ' ';
Run Code Online (Sandbox Code Playgroud)
你应该问问自己为什么你需要两个临时字符串(temporaryname1和temporaryname2)strswap()- 一个就够了.