为什么我的for循环不遍历我的char_array?

时间:2019-04-02 16:03:35

标签: c gcc

利用剥削的艺术一书中,它介绍了一个程序,该程序可以创建字符数组和整数数组。然后,它使指针遍历数组中的项目并打印它们各自的值和内存地址。在计算机上编译程序时,我只会得到整数,但是程序会在第一个字符处退出。

我已经尝试过在GDB中查看该程序,但是我认为我没有足够的经验来真正了解导致问题的原因。

下面是源代码:

#include <stdio.h>

int main() {
    int i;

    char char_array[5] = {'a', 'b', 'c', 'd', 'e'};
    int int_array[5] = {1, 2, 3, 4, 5};

    char *char_pointer;
    int *int_pointer;

    char_pointer = char_array;
    int_pointer = int_array;

    for(i=0; i <5; i++) {
        printf("[integer pointer] points to %p, which contains the integer %d\n", int_pointer, *int_pointer);
        int_pointer = int_pointer + 1;
    }

    for(i=0; i < 5; i++); {
        printf("[char pointer] points to %p, which contains the char '%c'\n", char_pointer, *char_pointer);
        char_pointer = char_pointer + 1;
    }
}

这是输出:

frinto@pwn:/tmp/dev$ ./pointer_types.out
[integer pointer] points to 0xffdde840, which contains the integer 1
[integer pointer] points to 0xffdde844, which contains the integer 2
[integer pointer] points to 0xffdde848, which contains the integer 3
[integer pointer] points to 0xffdde84c, which contains the integer 4
[integer pointer] points to 0xffdde850, which contains the integer 5
[char pointer] points to 0xffdde857, which contains the char 'a'

程序应该打印5个字符及其内存地址,但不是。知道为什么吗?

P.S。我在Ubuntu 18.10 x86_64

1 个答案:

答案 0 :(得分:2)

    for(i=0; i < 5; i++); {
        printf("[char pointer] points to %p, which contains the char '%c'\n", char_pointer, *char_pointer);
        char_pointer = char_pointer + 1;
    }

在左括号之前删除该分号。它所做的只是计数到5,然后执行一次body。