I'm learning C and have a question about this code:
Code:
#include <stdio.h>
int main() {
char date[] = "20091005";
char year[5] = "YYYY";
char month[3] = "MM";
char day[3] = "DD";
char *my_pointer = date;
year[0] = *(my_pointer);
year[1] = *(my_pointer + 1);
year[2] = *(my_pointer + 2);
year[3] = *(my_pointer + 3);
month[0] = *(my_pointer + 4);
month[1] = *(my_pointer + 5);
day[0] = *(my_pointer + 6);
day[1] = *(my_pointer + 7);
printf("The Year is: %s and the Month is: %s and the Day is: %s ", year, month, day);
return 0;
}
I changed it to this (changes marked in bold):
Code:
#include <stdio.h>
int main() {
int date[] = 20091005; /* Removed quotes and changed char to int */
int year[5] = 2009; /* Removed quotes, changed char to int, and changed YYYY to 2009 */
int month[3] = 10; /* Removed quotes, changed char to int, and changed MM to 10 */
int day[3] = 05; /* Removed quotes, changed char to int, and changed DD to 05 */
int *my_pointer = date; /* Changed char to int */
year[0] = *(my_pointer);
year[1] = *(my_pointer + 1);
year[2] = *(my_pointer + 2);
year[3] = *(my_pointer + 3);
month[0] = *(my_pointer + 4);
month[1] = *(my_pointer + 5);
day[0] = *(my_pointer + 6);
day[1] = *(my_pointer + 7);
printf("The Year is: %d and the Month is: %d and the Day is: %d ", year, month, day); /* Changed %s to %d */
return 0;
}
But it wouldn't compile due to this error:
Code:
practice1.c: In function 'main':
practice1.c:5: error: invalid initializer
practice1.c:7: error: invalid initializer
practice1.c:8: error: invalid initializer
practice1.c:9: error: invalid initializer
Why can I not use int instead of char for the pointer?