该程序的输出是:
XBCDO HELLE
有人可以解释为什么会这样吗?
#include<stdio.h>
void swap(char **p, char **q) {
char *temp = *p;
*p = *q;
*q = temp;
}
int main() {
int i = 10;
char a[10] = "HELLO";
char b[10] = "XBCDE";
swap(&a, &b);
printf("%s %s", a, b);
}
答案 0 :(得分:3)
你对指针和数组之间的区别感到困惑。 (它是语言的一个令人困惑的部分。)swap
需要指针指针,但是你已经指定了指向数组的指针。这是一个严重的错误,GCC警告即使你没有打开任何警告(它应该发出硬错误,但是一些非常非常古老的代码故意做这样的事情,他们不想打破那个。)
$ gcc test.c
test.c: In function ‘main’:
test.c:16:10: warning: passing argument 1 of ‘swap’ from incompatible pointer type [-Wincompatible-pointer-types]
swap(&a, &b);
^
test.c:3:1: note: expected ‘char **’ but argument is of type ‘char (*)[10]’
swap(char **p, char **q)
^~~~
test.c:16:14: warning: passing argument 2 of ‘swap’ from incompatible pointer type [-Wincompatible-pointer-types]
swap(&a, &b);
^
test.c:3:1: note: expected ‘char **’ but argument is of type ‘char (*)[10]’
swap(char **p, char **q)
^~~~
错误导致程序具有未定义的行为 - 它根本不需要做任何有意义的事情。
您可能尝试编写的程序如下所示:
#include <stdio.h>
static void swap(char **p, char **q)
{
char *temp = *p;
*p = *q;
*q = temp;
}
int main(void)
{
char a[10] = "HELLO";
char b[10] = "XBCDE";
char *c = a;
char *d = b;
swap(&c, &d);
printf("%s %s", c, d);
}
这个程序的输出是XBCDE HELLO
,我认为这是你所期待的。 c
和d
实际上是指针,它们设置为指向数组a
和b
的第一个元素;应用于swap
和c
时,d
按预期工作。
如果c
和d
与a
和b
不同,那么你需要掌握好的C教科书,你需要阅读有关指针的章节并进行所有练习。 (如果它没有关于指针的至少一整章,通过练习,它不是一本好的C教科书。)