So I've been experimenting with pointers for a while and a few questions have come up. In the code below, first of all, when I print the memory addresses for each of:
pHours++ - pHours - pHours + sizeof(char), I get the following results:
1989086632 - 1989086636 - 1989086636.
Shouldn't the value of pHours++ be by 4 units (Btw, doesn't C normally allocate 1 byte instead of 4 for storing a char?) larger, instead of smaller, than pHours's value?
Moreover, why is pHours + sizeof(char)'s value the same as pHours's? In the code I've written below, it becomes clear that the addition of sizeof(char) does change the address at which the pointer points, since when I omit it in the function's last printing statement, I get a segmentation fault (*nHours holds no value).
Also, why do I get a segmentation fault when I write nHours++, but not when I do the same for skata (skata++) or pHours (pHours++)?
Oh, two more things. Visual Studio's compiler gives me an error for not initializing *nHours and *skata before using them, but using an online compiler I'm allowed to do so. Why is this a mandatory practice in VS?
Also, why is it preferrable to use the format string %p instead of %d for referring to memory addresses?
That's all for now. Thank you in advance! :)
#include <stdio.h>
#define MinutesPerHour 60
void ConvertTimeToHM(int time, int *pHours, int *pMinutes);
int main()
{
int time, hours, minutes;
printf("Enter a time duration in minutes: ");
scanf("%d", &time);
ConvertTimeToHM(time, &hours, &minutes);
printf("HH:MM format: %d:%02d\n", hours, minutes);
return 0;
}
void ConvertTimeToHM(int time, int *pHours, int *pMinutes)
{
*pHours = time / MinutesPerHour;
int *nHours, *skata, *kHours;
*pMinutes = time % MinutesPerHour;
//nHours = pHours;
//nHours++;
skata++;
printf("%d %d %d\n", pHours++, pHours, pHours + sizeof(char));
skata = nHours + 3 * sizeof(char);
*skata = 19;
printf("%d\n", *(nHours + 3 * sizeof(char)));
}