简体   繁体   中英

Can someone explain output of this program?

The output of this program is:

XBCDO HELLE

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 . 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 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. c and d are actually pointers, and they are set to point to the first elements of the arrays a and b ; swap works as expected when applied to c and d .

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. (If it doesn't have at least one entire chapter on pointers, with exercises, it's not a good C textbook.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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