简体   繁体   English

有人可以解释这个程序的输出吗?

[英]Can someone explain output of this program?

The output of this program is:这个程序的输出是:

XBCDO HELLE XBCDO 海尔

Can someone explain why this is so?有人可以解释为什么会这样吗?

#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);
}

You are confused about the difference between pointers and arrays.您对指针和数组之间的区别感到困惑。 (It is a confusing part of the language.) swap expects pointers to pointers, but you have given it pointers to arrays . (这该语言的一个令人困惑的部分。) swap需要指向指针的指针,但您已经给了它指向数组的指针。 This is such a serious mistake that GCC warns about it even if you don't turn on any warnings (it ought to issue hard errors, but some very, very old code does stuff like this intentionally and they don't want to break that).这是一个如此严重的错误,即使您没有打开任何警告,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)
 ^~~~

The mistake causes the program to have undefined behavior - it doesn't have to do anything that makes any sense at all.该错误导致程序具有未定义的行为——它根本不需要做任何有意义的事情。

The program you probably were trying to write looks like this:您可能尝试编写的程序如下所示:

#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);
}

The output of this program is XBCDE HELLO , which I think is what you were expecting.该程序的输出是XBCDE HELLO ,我认为这正是您所期望的。 c and d are actually pointers, and they are set to point to the first elements of the arrays a and b ; cd实际上是指针,它们被设置为指向数组ab的第一个元素; swap works as expected when applied to c and d .当应用于cd时, swap按预期工作。

If it doesn't make any sense that c and d are different from a and b , you need to get your hands on a good C textbook and you need to read the chapter on pointers and do all the exercises.如果cdab不同没有任何意义,那么您需要掌握一本好的 C 教科书,并且需要阅读有关指针的章节并完成所有练习。 (If it doesn't have at least one entire chapter on pointers, with exercises, it's not a good C textbook.) (如果它没有至少一整章关于指针的内容,加上练习,它就不是一本好的 C 教科书。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM