我怎样才能让一个字符串数组互换它的成分与交换功能?

问题描述 投票:2回答:3

问题是,这个代码将不能互换这两个字符串。我是新来编程,但是我可以告诉大家,问题是,交换功能,但我不知道如何解决它。

我尝试添加的strcpy“=”,在交换代替,但没有奏效。

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

void swap(char *t1, char *t2) {
    char *t;
    t=t1;
    t1=t2;
    t2=t;
}
int main() {
    char *s[2] = {"Hello", "World"};
    swap(s[0], s[1]);
    printf("%s\n%s", s[0], s[1]);
    return 0;
}
c swap pass-by-value function-call
3个回答
6
投票

你想在这里使用了参数,因为你的字符串表示为指针,你需要指针的指针:

void swap(char **t1, char **t2) {
    char *t;
    t = *t1;
    *t1 = *t2;
    *t2 = t;
}

这样称呼它:

swap(&s[0], &s[1]);

我尝试添加的strcpy“=”,在交换代替,但没有奏效。

为什么不工作的原因是因为琴弦实际上是存储在程序的二进制文件,因此不能被修改,并与strcpy你会写他们。如果您将它们复制到堆栈或堆代替,那么你可以做strcpy掉。当然,这将是不仅仅是交换指针效率较低,但是这是它会是什么样子:

void swap(char *t1, char *t2) {
    char buf[16]; // needs to be big enough to fit the string
    strcpy(buf, t1);
    strcpy(t1, t2);
    strcpy(t2, buf);
}

你还需要s的定义修改为一个类似于

char s[2][16] = { "Hello", "World" }; // strings are copied to the stack now

2
投票

仔细检查类型。

什么,你得为阵成员指针(串文字的开始元素)。您需要交换的成员的方式,使它们指向其他的字符串常量。所以,你需要改变这些指针本身。

所以,你需要传递指针这些指针,然后再到被调用函数的变化。

这样做

swap(&(s[0]), &(s[1]));

然后,在被调用的函数:

void ptrSwap(char **t1, char **t2) {
    char *temp;
    temp=*t1;
    *t1=*t2;
    *t2=temp;
}

加分点:命名功能(和变量,也如适用)有意义。


2
投票

你需要传递指针的指针,即在数组中的位置的字符串都存在,这样就可以互换,并把正确的地址存在的地址。

试试下面的代码:

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

void swap(char **t1, char **t2) {
    char *t;
    t=*t1;
    *t1=*t2;
    *t2=t;
}
int main() {
    char *s[2] = {"Hello", "World"};
    swap(&s[0], &s[1]);
    printf("%s\n%s", s[0], s[1]);
    return 0;
}

输出:

World
Hello
© www.soinside.com 2019 - 2024. All rights reserved.