char model[10][15] = {"Honda","Audi","Ferrari","Jeep","Toyota","Bugatti","Ford","Jensen","Porsche","Suzuki"};
int price[10][15] = {750000,650000,950000,300000,900000,1000000,400000,750000,300000,800000};
int remain[10][15] = {3,4,5,3,3,7,8,2,1,2,2};
for(i=0;i<11;i ){
printf("\n%s\t %d\t %d\t",model[i],price[i],remain[i]);
}
I tried all sorts of things but nothing worked... I'm a new C programmer (just jumped from JAVA)
CodePudding user response:
Because you are declaring your arrays wrong.
char *model[11] = {"Honda","Audi","Ferrari","Jeep","Toyota","Bugatti","Ford","Jensen","Porsche","Suzuki"};
int price[11] = {750000,650000,950000,300000,900000,1000000,400000,750000,300000,800000,9000};
int remain[11] = {3,4,5,3,3,7,8,2,1,2,2};
CodePudding user response:
model is an array of 10 arrays of 15 char.
Therefore model[i] is one of those 10 arrays; it is an array of 15 char.
When an array is used in an expression other than as the operand of sizeof or unary & or as a string literal used to initialize an array, it is automatically converted to a pointer to its first element. Therefore, using model[i] as an argument to printf passes a pointer to the first element of the array model[i].
With %s, printf expects a pointer to a char, and it prints the string of characters it finds starting at that location in memory. So passing model[i] passes a pointer which works with %s.
price is an array of 10 arrays of 15 int.
Therefore price[i] is one of those 10 arrays; it is an array of 15 int.
Passing price[i] to printf passes a pointer to the first element of the array price[i].
With %d, printf expects an int value, not a pointer, so passing price[i] does not work.
Instead, you want price to be an array of 10 int. Then price[i] will be an int, not an array of int. To do that, change the definition:
int price[10] = {750000,650000,950000,300000,900000,1000000,400000,750000,300000,800000};
int remain[10] = {3,4,5,3,3,7,8,2,1,2,2};
Then passing price[i] to printf will pass an int, not a pointer.
