如何使字符串数组与交换函数交换它的组件? [英] How I can make a string array interchange it's components with a swap function?

查看:70
本文介绍了如何使字符串数组与交换函数交换它的组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

问题是这段代码不会交换这两个字符串.我是编程新手,但我可以看出问题在于交换函数,但我不知道如何修复它.

我尝试在交换中添加 strcpy 而不是=",但没有奏效.

#include #include 无效交换(char *t1,char *t2){图表;t=t1;t1=t2;t2=t;}int main() {char *s[2] = {"你好", "世界"};交换(s[0],s[1]);printf("%s\n%s", s[0], s[1]);返回0;}

解决方案

您想在此处使用 out 参数,并且由于您的字符串表示为指针,因此您需要指向指针的指针:

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

这样称呼它:

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

<小时><块引用>

我尝试在交换中添加 strcpy 而不是=",但没有奏效.

这行不通的原因是因为字符串实际上存储在程序的二进制文件中,因此无法修改,并且使用 strcpy 可以覆盖它们.如果您将它们复制到堆栈或堆中,那么您可以使用 strcpy 进行交换.当然,这比仅仅交换指针效率要低,但它看起来像这样:

void swap(char *t1, char *t2) {字符缓冲区[16];//需要足够大以适合字符串strcpy(buf, t1);strcpy(t1, t2);strcpy(t2, buf);}

此外,您还需要将 s 的定义更改为类似于

char s[2][16] = { "Hello", "World" };//字符串现在被复制到堆栈中

The problem is that this code won't interchange these 2 strings. I'm new to programming but I can tell that the problem is that swap function, but I do not know how to fix it.

I tried to add strcpy instead of "=" in swap but that didn't worked.

#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;
}

解决方案

You want to use out parameters here, and since your strings are represented as pointers, you need pointers to pointers:

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

Call it like this:

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


I tried to add strcpy instead of "=" in swap but that didn't worked.

The reason why that doesn't work is because the strings are actually stored in the program's binary and therefore can't be modified, and with strcpy you would write over them. If you copy them to the stack or the heap instead then you can do the swap with strcpy. Of course that's going to be less efficient than just swapping the pointers, but this is how it would look like:

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);
}

Also you would need to change the definition of s to something akin to

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

这篇关于如何使字符串数组与交换函数交换它的组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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