【问题标题】:warning: array subscript is above array bounds [-Warray-bounds] in module [closed]警告:数组下标高于模块中的数组边界[-Warray-bounds] [关闭]
【发布时间】:2016-10-30 11:00:13
【问题描述】:
static int myarray[2]={-1,234};
module_param_array(myarray,int,&arrayargc,0);
MODULE_PARM_DESC(myarray,"Integer Array");

static int __init module_init_2(void)
{
 int i;
  for(i=0;i< (sizeof myarray/sizeof(int));i++);
{

printk(KERN_INFO "myarray[%d] is %d",i,myarray[i]);

}

我正在编写一个简单的模块来获取一些命令行输入。在编译期间它会发出警告

warning: array subscript is above array bounds [-Warray-bounds]
printk(KERN_INFO "myarray[%d] is %d",i,myarray[i]);

为什么它会发出警告,因为循环似乎一直运行到 i=2,我看到了一些关于此的问题,但这对我没有太大帮助

【问题讨论】:

  • 您忘记了"Option#N ..." 字符串之间的逗号。 C 将其视为单个字符串。投票结束是一个错字。
  • 帮助检测到吸血鬼。
  • 无法重现,但顺便说一句,char m; 应该是 int m;,这是 getchar() 返回的类型。
  • @SaudFarooqui 那是因为您使用scanf 进行用户输入,这是一个错误。此外,这个问题在 SO 上有大约 500 个重复。
  • 添加了两个缺少的逗号后,我无法重现您的下一个问题。请使用Minimal, Complete, and Verifiable example 提出一个新问题,以显示该问题。 “完整”意味着您的代码可以复制/粘贴到文本编辑器中并完全按原样编译,以演示错误。

标签: c arrays for-loop printk


【解决方案1】:

您最开始的printf 为三个字符串指定了三个%s,但您只为那个printf 提供了一个字符串,因此崩溃了。

风向标评论的注释:

请记住,C 编译器将连接仅由空格分隔的字符串文字。

这意味着即使您在三行中编写了三个单独的“选项 #1”、“选项 #2”等,它们仍然算作 一个 字符串(在连接之后。通过添加来解决此问题每行末尾的逗号以防止连接(因此您将拥有三个单独的字符串)。

【讨论】:

  • 是的,你是对的,我添加了你的评论,应该更清楚地解释 OP 问题。
  • 我喜欢初学者生成您从未想过的“创造性”错误的方式。几乎是艺术。
  • 我已经正确了。现在的问题是程序打印选项然后绕过 m=getchar 并直接跳转到下一个 printf。你能告诉我原因吗?
  • m 对于getchar 应该是int - 除此之外它应该可以正常工作
  • 我已经做了 m int 但它仍然在绕过
【解决方案2】:

你可以试试这个。我假设您想要输出成功读取的两个值。

#include <stdio.h>
#include <stdlib.h>

int
main(int argc, char const *argv[]) {
    int period, time;

    const char micro_sec = 'u';
    const char mili_sec = 'm';
    const char sec = 's';

    printf("\nSelect unit of Time period: \n");

    printf("\nOption 1: %c for micro seconds\n"
             "Option 2: %c for mili seconds\n"
             "Option 3: %c for seconds\n", 
              micro_sec, mili_sec, sec);

    printf("\nEnter unit of Time Period: ");

    period = getchar();

    if (period == micro_sec || period == mili_sec || period == sec) {
        printf("Enter Time Period: ");

        if (scanf("%d", &time) != 1) {
            printf("Error reading time!\n");
            exit(EXIT_FAILURE);
        }

        printf("\nUnit of time: %c\n", period);
        printf("Time Period: %d\n", time);

    } else {
        printf("\nIncorrect unit of time entered.\n");
    }

    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-11-13
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 2013-02-07
    • 2017-08-07
    • 1970-01-01
    相关资源
    最近更新 更多