为什么使用此代码无法交换2个字符数组? [英] Why swapping of 2 character array is not possible with this code ?

查看:76
本文介绍了为什么使用此代码无法交换2个字符数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int i,j;
    char c1[100]={"MY name is Anup"};
    char c2[100]={"MY name is kumar"};
    char temp[200];
    printf("before swapping\n");
    printf("C1=%s\nC2=%s",c1,c2);
    i=0;j=0;
    while(c1!='\0')
    {
        temp[j]=c1[i];
        i++;j++;
    }
    temp[j]='\0';
    i=0;j=0;
    while(c2!='\0')
    {
        c1[j]=c2[i];
        i++;j++;
    }
    c1[j]='\0';
    i=0;j=0;
    while(temp[i]!='\0')
    {
        c2[i]=temp[j];
        i++;j++;
    }
    //c2[i]='\0';
    printf("After swapping\n");
    printf("C1=%s\nC2=%s",c1,c2);
    return 0;
}





我的尝试:



我试过上面的代码编写方式..但是没有正确执行..我认为这可能是由于Fragmentation Fault ..我知道我哪里出错..



What I have tried:

I tried above code writing in this way.. But not executing properly.. I think it may be due to Fragmentation Fault..let me know where I went wrong..

推荐答案

while(c1!='\0')   //----> comparing a pointer to '/0'
{
    temp[j]=c1[i];
    i++;j++;       // why have 2 variables here, they are always the same value?
}
temp[j]='\0';
i=0;j=0;
while(c2!='\0')      //----> comparing a pointer to '/0'
{
    c1[j]=c2[i];
    i++;j++;     // why have 2 variables here....?

}





我没有看过你的所有逻辑,但这些东西都很突出。



I've not looked at all your logic, but these things stood out.


你的代码在复制字符时是正确的,但在进行\0比较时你需要使用相同的语法。

你应该试试这段代码。

Your code is correct when it comes to copying chars, but you need to use the same syntax when doing \0 compare.
You should try this code.
i=0;j=0;
while(c1[i]!='\0')  // a little change here
{
    temp[j]=c1[i];
    i++;j++;
}
temp[j]='\0';
i=0;j=0;
while(c2[i]!='\0')  // a little change here
{
    c1[j]=c2[i];
    i++;j++;
}
c1[j]='\0';
i=0;j=0;
while(temp[i]!='\0')
{
    c2[j]=temp[i];  // a little change here
    i++;j++;
}
c2[i]='\0';  // a little change here



或者你也可以简化代码


Or you can also simplify the code

i=0;
while(c1[i]!='\0')
{
    temp[i]=c1[i];
    i++;
}
temp[i]='\0';
i=0;
while(c2[i]!='\0')
{
    c1[i]=c2[i];
    i++;
}
c1[i]='\0';
i=0;
while(temp[i]!='\0')
{
    c2[i]=temp[i];
    i++;
}
c2[i]='\0';


这篇关于为什么使用此代码无法交换2个字符数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆