字符串交换适用于char **,但不适用于char * [英] string swapping works well with char ** but not with char *

查看:186
本文介绍了字符串交换适用于char **,但不适用于char *的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在这个程序中,我已经将前两个名字换成了,其中
$ b

In this program I have swapped the first 2 names

#include<stdio.h>
void swap(char **,char **);
main()
{
 char *name[4]={"amol", "robin", "shanu" };
 swap(&name[0],&name[2]);
 printf("%s %s",name[0],name[2]);
}
void swap(char **x,char **y)
 {
 char *temp;
 temp=*x;
 *x=*y;
 *y=temp;
 }

这个程序运行完美,但是当我使用函数交换(char *,char *)它不交换地址为什么?为什么我必须使用指针指针?

This programs runs perfectly but when I use the function swap(char *,char *) it does not swap the address why? why I have to use pointer to pointer?

推荐答案

我假设您明白,要交换整数,您将具有 swap(int *,int *)

I assume you understand that to swap integers you would have function like swap(int *, int *)

同样,当你想交换字符串 char * 。您需要像 swap(char **,char **)这样的函数。

Similarly, When you want to swap strings which is char *. You would need function like swap(char **, char **).

在这种情况下,他们的指针并交换他们的内容(否则一旦函数返回,值就不会被交换)。对于整数内容,指针是 int * ,如果字符串的内容是 char * 指向它的指针是 char **

In such cases, you take their pointers and swap their content (otherwise values will not be swapped once function returns). For integer content, pointer is int * and in case of strings content is char * pointer to it is char **.

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

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