为什么C中的此字符串交换函数不交换字符串? [英] why is this string swap function in C not swap the strings?

查看:65
本文介绍了为什么C中的此字符串交换函数不交换字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试使用指针交换字符串,但我不知道为什么这不交换字符串?

I tried to swap strings using pointers but I do not know why is this not swapping the strings?

所以有人能解释我为什么会发生并纠正它吗?

so can anyone explain me why is it happening and also correct it?

#include<stdio.h> 
void swap(char *str1, char *str2) 
{ 
  char *temp = str1; 
  str1 = str2; 
  str2 = temp; 
}   
   
int main() 
{ 
  char *str1 = "geeks"; 
  char *str2 = "forgeeks"; 
  swap(str1, str2); 
  printf("str1 is %s, str2 is %s", str1, str2); 
  getchar(); 
  return 0; 
} 

输出:

str1 is geeks, str2 is forgeeks

推荐答案

您正在按值传递指针,以便修改其副本,而不是原始的 str1 str2 .

You're passing the pointers by value so their copies are modified, not the original str1 and str2.

您可以修改 swap 的签名,以将指针传递给指针,然后通过取消引用来修改其值:

You could modify the signature of swap to pass a pointer to a pointer, then modfying its value by dereferencing it:

void swap(char** str1, char** str2) 
{ 
  char* temp = *str1; 
  *str1 = *str2; 
  *str2 = temp; 
} 

还有

char* str1 = "geeks"; 
char* str2 = "forgeeks"; 
swap(&str1, &str2); 

这篇关于为什么C中的此字符串交换函数不交换字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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