c - 指针在 void 函数中交换值,但不会返回交换后的值

标签 c string pointers

我正在尝试交换作为 char 指针传入的两个字符串。

在调试中,我在被调用函数的末尾得到了正确的答案,但在函数结束后返回的值返回与传入的值相同的值。这是代码

#include <stdio.h>

int main(int argc, char const *argv[]) {
  char *s1, *s2;
  s1 = "12345678";
  s2 = "87654321";

  printf("s1 is %s\n", s1);
  printf("s2 is %s\n", s2);
  strswap(s1, s2);
  printf("s1 is now %s\n", s1);
  printf("s2 is now %s\n", s2);
}

以及函数本身的代码

#include <stdio.h>

void strswap(char *s1, char *s2){
    char *temp;

    temp = s1;
    printf("temp: %s\n", temp);
    s1 = s2;
    printf("s1: %s\n", s1);
    s2 = temp;
    printf("s1: %s\n", s1);
    printf("s2: %s\n", s2);
    printf("temp: %s\n", temp);
}

最佳答案

我为了交换字符串,首先你不能只使用常量字符串文字,因为它们是不可变的。将字符串文字分配给 char * 被认为是不好的做法,除非您正确知道要实现的目标。阅读此linkthis还。您应该使用静态/动态分配的字符串。

正如其他人所说,您是按值传递字符指针,因此您在 strswap() 中所做的任何更改都不会反射(reflect)在 main 函数中。由于一些局部变量被修改,并且当控制权脱离这些函数时它们会被销毁。您应该像上述答案之一一样传递 char ** 。我建议使用静态分配的字符串并使用 strcpy 进行字符串复制操作,如下所示:

#include <stdio.h>
#include <string.h>

#define MAX_SIZE 1000

void strswap(char *s1, char *s2){
    char tempStr[MAX_SIZE];
    strcpy(tempStr, s1);
    strcpy(s1, s2);
    strcpy(s2, tempStr);
}

int main(int argc, char const *argv[]) {
    char aString1[MAX_SIZE] = "Rohan", aString2[MAX_SIZE] = "Rohit";

    printf("s1 is %s\n", aString1);
    printf("s2 is %s\n", aString2);
    strswap(aString1, aString2);
    printf("s1 is now %s\n", aString1);
    printf("s2 is now %s\n", aString2);
    return 0;
}

关于c - 指针在 void 函数中交换值,但不会返回交换后的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46359585/

相关文章:

c - tcc "lvalue expected"错误

javascript - 多个子字符串的 jquery/javascript 检查字符串

delphi - 为什么会出现内存泄漏以及如何修复它?

c - 字符指针的行为

c - 调用 void 函数时出现段错误

c - 接受 int64_t 的输入

c - 将 GStreamer 添加到 Eclipse

c++ - 如何在 OpenCV 中使用 cv::createButton 原型(prototype)

Java 字符串到字节数组的错误转换

c - string.h 中的 gcc 函数会破坏 UTF-8 字符串吗?