c - 'C' 二维数组的段错误

标签 c arrays codeblocks segmentation-fault

谁能解释一下为什么这段代码不起作用?

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

void findAndPrint(char *arr[], int year, int month, int day);

int main()
{
    char *dayTab[] = {
        {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
        {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
    };
    findAndPrint(dayTab, 3, 3, 3);
    getchar();
    return 0;
}

void findAndPrint(char *arr[], int year, int month, int day ){
    int d = 0;
    if(month > 12 || month < 1 || day > 31 || day<1)
        return;
    int leap = ((year%4==0 && year%100!=0) || year%400 == 0)?1:0;
    int i;
    for(i=0; i<month-1; i++){
        d += arr[leap][i];
    }
    d+= day;
    printf("Day = %d", d);
}

IDE(Code::Blocks) 写入“程序接收到信号 SIGSEGV。段错误。”

最佳答案

首先,您需要一个二维字符数组,不是一个指向字符的指针数组。

char dayTab[][12] = {
    {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
    {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};

然后您必须更改函数以接受该类型。

void findAndPrint(char arr[][12], int year, int month, int day ) ;

其余的看起来还不错。

尝试使用参数:

findAndPrint(dayTab, 2014, 10, 12);

给我们一天:285

这是正确的,耶!

关于c - 'C' 二维数组的段错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26327834/

相关文章:

c - 使用代码块进行套接字编程

C 增加 char 数组的大小

php - 如何连接两个或多个表,每个表具有相同的列名

c++ - 代码块未正确显示程序参数

c - 意外错误 :"Dereferencing pointer to incomplete type"with code::blocks,c 语言

vim - 是否可以在 Code::Blocks 中使用 vi 模式?

c - 从堆栈中弹出,程序无限循环

c - 迷你XML : parsing xml in C

javascript - 计算所有具有相同未知类名的兄弟元素

arrays - 结构体数组中的变量变化