0
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,我看到了一些关于此的问题,但这对我没有太大帮助

4

2 回答 2

3

你一开始就为三个字符串printf指定了三个,但你只为那个提供了一个字符串,所以崩溃了。%sprintf

风向标评论的注释:

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

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

于 2016-10-30T11:02:59.250 回答
0

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

#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;
}
于 2016-10-30T12:39:21.557 回答