gpt4 book ai didi

c - 在 C 中交换双指针

转载 作者:行者123 更新时间:2023-11-30 20:13:02 26 4
gpt4 key购买 nike

这是我的代码;我想交换下面的名字。我正在练习这个;

我收到的错误是

Segmentation fault

如有任何帮助,我们将不胜感激。

void nameSwap(char **wife[3],char **husband[3])
{
int i;
char **tmp[3];
for(i=0;i<3;i++)
{

*tmp[i]=*wife[i];
*wife[i] = *husband[i];
*husband[i] = *tmp[i];
}

int main(int argc,char *argv[])
{
char *name1[3]={"Chicago","University","Computer"};
char *name2[3]={"I","Love","Uchicago"};

int k;
char **p1[3];
char **p2[3];

for(k=0;k<3;k++)
{
*p1[k]=name1[k];
*p2[k]=name2[k];
}

for(k=0;k<3;k++)
{
printf("%s %s\n",*p1[k],*p2[k]);
}

nameSwap(&p1[3],&p2[3]);

for(k=0;k<3;k++)
{
printf("%s %s\n",*p1[k],*p2[k]);
}
return 0;

}

最佳答案

双指针的意思

char ** 的情况

#include <stdio.h>

void nameSwap(char ***wife, char ***husband){
char **tmp;

tmp = *wife;
*wife = *husband;
*husband = tmp;
}

int main(void){
char *name1[3]={"Chicago","University","Computer"};
char *name2[3]={"I","Love","Uchicago"};

int k;
char **p1;
char **p2;

p1 = name1;
p2 = name2;

for(k=0;k<3;k++){
printf("%s %s\n", p1[k], p2[k]);
}

nameSwap(&p1, &p2);

for(k=0;k<3;k++){
printf("%s %s\n", p1[k], p2[k]);
}
return 0;
}
<小时/>

指向char *var_name[3]的指针的情况

#include <stdio.h>

void nameSwap(char *(**wife)[3], char *(**husband)[3]){
char *(*tmp)[3];

tmp = *wife;
*wife = *husband;
*husband = tmp;
}

int main(void){
char *name1[3]={"Chicago","University","Computer"};
char *name2[3]={"I","Love","Uchicago"};

int k;
char *(*p1)[3];
char *(*p2)[3];

p1 = &name1;
p2 = &name2;

for(k=0;k<3;k++){
printf("%s %s\n", (*p1)[k], (*p2)[k]);
}

nameSwap(&p1, &p2);

for(k=0;k<3;k++){
printf("%s %s\n", (*p1)[k], (*p2)[k]);
}
return 0;
}

关于c - 在 C 中交换双指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33060346/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com