数组元素反向打印

时间:2019-10-16 14:34:57

标签: c arrays debugging c-strings string-literals

我想从数组中打印出所有元素以调试程序。

这是for循环,用于打印出数组的所有元素

for(int i = 0; i <= 9; i++) {
        printf("Words: %s\n", &words[i]);
    }

我有一个包含const char数组的头文件。这是一项任务所必需的。 我知道将它们放在头文件中可能不是一个好习惯。

const char *words[10] = {'foo', 'bar', 'hello', 'world'};

运行此代码时,我的输出很奇怪,因为它将所有内容向后打印。

Keywords: oof
Keywords: rab
Keywords: olleh
Keywords: dlrow

有时,它甚至会在每个关键字的末尾添加随机句号。 为什么是这样?除了那我什么都没写。

2 个答案:

答案 0 :(得分:3)

对于初学者,请使用字符串文字而不是字符文字

const char *words[10] = {"foo", "bar", "hello", "world"};

请注意,从索引4开始的数组的所有元素均由空指针初始化。

只需使用

for(int i = 0; words[i] != NULL && i < 10; i++) {
        printf("Keywords: %s\n", keyWords[i]);
                                 ^^^^^^^^ 
    }

这是一个演示程序

#include <stdio.h>

int main(void) 
{
    const char *words[10] = {"foo", "bar", "hello", "world"};

    for ( size_t i = 0; words[i] != NULL && i < 10; i++ ) puts( words[i] );

    return 0;
}

其输出为

foo
bar
hello
world

请注意,游览代码段中有错别字。使用名称wordskeywords命名数组。

答案 1 :(得分:0)

在编写scanf而不是printf时,仅应使用“&keywords”。 请执行以下操作:

[E01, 2019, 07, ... 2.328306436539e-09, 9.999000000000e+08]