首页 > 解决方案 > 使用指针数组打印字符串

问题描述

试图修改编码考试,我遇到了这张幻灯片。你们中的任何人都可以帮助我了解如何从指向数组的指针打印字符串吗?这是代码示例:

#include <stdio.h>

int main(void)
{
    size_t i;
    const char *suit[4] = { "Hearts", "Diammonds", "Clubs", "Spades" };

    printf("The strings in array const char*suit[4] is:\n\n");


    for (i = 0; i < 5; i++)
    {
        printf("const char *suit[%u] is: %s\n", i, suit[i]);
    }
}

当我打印时,我得到这个输出:

The strings in array const char*suit[4] is:

const char *suit[0] is: Hearts
const char *suit[1] is: Diammonds
const char *suit[2] is: Clubs
const char *suit[3] is: Spades

但是,它也带有此错误。“Pointer Practice.exe 中的 0x7AAD170C (ucrtbased.dll) 引发异常:0xC0000005:访问冲突读取位置 0xCCCCCCCC。”

为什么会出现错误?如何打印相同的输出,但没有错误?

提前谢谢你们!

标签: c

解决方案


一个简单的修复!您的数组中只有 4 个元素,但迭代了 5 次。尝试访问suit[5]将引发分段错误(在 Linux 上)或访问冲突(在 Windows 上)。这些错误发生在您访问不应该访问的内存时(如果您尝试访问 0xEABCC8,但您无权访问它,您将遇到这些错误之一)。尝试将您的最大值更改为 4,而不是 5。
在 C(以及基本上所有其他语言)中,索引在索引时从 0 开始,但在初始化时从 1 开始。例子:

const int foo[4] = { 6, 9, 3, 2}; // Creates an array with 4 elements.
foo[4] // Gets the fifth element since it start at zero,
foo[0] // thus this is the first element.

推荐阅读