交换两个字符串指针 [英] Swapping two string pointers

查看:134
本文介绍了交换两个字符串指针的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我必须为char []在C和我希望他们之间切换,只swaping指针
到数组,而不是一个字符在一个时间,所以我写了这个code:

i have to char[] in C and i wanted to swap between them, by only swaping the pointer to the array and not one char at a time so i wrote this code:

#include <stdio.h>
void fastSwap (char **i, char **d)
{
    char *t = *d;
    *d = *i;
    *i = t;
}
int main ()
{
    char num1[] = "012345678910";
    char num2[] = "abcdefghujk";
    fastSwap ((char**)&num1,(char**)&num2);
    printf ("%s\n",num1);
    printf ("%s\n",num2);
    return 0;
}

我得到这个输出(注意最后4个字符)

I get this output (note the last 4 characters)


abcdefgh8910
01234567ujk

当我想到:


abcdefghujk
012345678910

请注意:我的工作在64位Linux系统

NOTE: I am working on a 64 bit Linux System.

推荐答案

您不能修改 NUM1 NUM2 ,您的code应该工作,如果你的测试是不是:

You can't modify the addresses of num1 and num2, your code should work if your test was instead:

int main ()
{
    char num1[] = "012345678910";
    char num2[] = "abcdefghujk";
    char *test1 = num1;
    char *test2 = num2;
    fastSwap (&test1,&test2);
    printf ("%s\n",test1);
    printf ("%s\n",test2);
    return 0;
}

这篇关于交换两个字符串指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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