'C'分段故障与二维数组 [英] 'C' Segmentation fault with 2d array
本文介绍了'C'分段故障与二维数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有人能解释我为什么这个code不起作用?
Can anybody explain me why this code doesn't work?
#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 ::块)写道:计划接收信号SIGSEGV,分割过错。
IDE(Code::Blocks) writes "Program received signal SIGSEGV. Segmentation fault."
推荐答案
首先,你需要字符的二维数组,的不的指针数组为字符。
First you need a 2d array of characters, not an array of pointers to characters.
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}
};
然后,你必须改变函数接受该类型。
Then you have to change the function to accept that type.
void findAndPrint(char arr[][12], int year, int month, int day ) ;
其余看起来不错。
The rest looks ok.
与参数尝试:
findAndPrint(dayTab, 2014, 10, 12);
让我们的一天: 285
这是正确的,yaaay!
Which is correct, yaaay!
这篇关于'C'分段故障与二维数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文