C K&R: printf pointer = nil?
-
21-12-2019 - |
Question
int *month, *day;
printf("%p,%p\n", month, day);
Executing the codesample above returns: 0x7fffeda86190,(nil)
Also i get a segmentation fault whenever i assign something to the *day pointer as demonstrated in the code below coming from K&R chapter 5.7:
What is causing this behavior and where can i learn more about this kind of behavior?
static char daytab[2][13] = {
{0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
{0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
};
int main()
{
int *month, *day;
printf("%p,%p\n", month, day);
month_day(2009, 78, month, day);
printf("%d,%d\n", *month, *day);
}
int day_of_year(int year, int month, int day)
{
int i, leap;
leap = year%4 == 0 && year%100 != 0 || year%400 == 0;
for (i = 1; i < month; i++)
day+= daytab[leap][i];
return day; /*day of the year*/
}
int month_day(int year, int yearday, int *pmonth, int *pday)
{
int i, leap;
leap = year%4 == 0 && year%100 != 0 || year%400 == 0;
for (i = 1; yearday > daytab[leap][i]; i++)
yearday -= daytab[leap][i];
*pmonth = i;
printf("%d,%d\n", *pmonth, yearday);
*pday = yearday;
}
Solution
Your month
and day
pointer point to nowhere (or some random location). Let's look at the day
pointer.
*day = value;
When you're trying to write the memory pointed by day
, your OS will figure out writing to this address (0?) makes no sense and kills your program.
Solution 1: Use malloc
to dynamically allocate some memory and point day
there:
day = (int*)malloc(sizeof(int));
*day = 10; //this is now legal
You could also make the pointers point memory inside some array etc.
Solution 2: Pass pointers to 'regular' variables to the month_day
function:
int mymonth, myday;
month_day(2009, 78, &mymonth, &myday);
// now mymonth and myday should have expected values
Hope this helps.