I've written the following sample program as a way to help improve my understanding of passing pointers to a function, and it currently works:
#include "stdio.h"
typedef struct Car {
char* name;
unsigned int price;
} Car;
void print_cars(Car* cars[]) {
for (int i=0; cars[i] != NULL;i++) {
printf("\n<Car: %s, Price: $%d>", car->name, car->price);
}
}
void depreciate(Car* cars[]) {
for (int i=0; cars[i] != NULL; i++) {
cars[i]->price = cars[i]->price * 0.95;
}
}
int main(int argc, char* argv[]) {
Car chevy = {.name = "Chevy", .price = 45000};
Car mazda = {.name = "Mazda", .price = 30000};
Car ferrari = {.name = "Ferrari", .price = 200000};
Car* my_cars[] = {&chevy, &mazda, &ferrari, NULL};
print_cars(my_cars);
printf("\n--------- Depreciating -----------");
depreciate(my_cars); // <-- ignoring this
print_cars(my_cars);
return 1;
}
Ignoring the line that modifies the value of the struct, would it be possible to do the print_cars
function without using a pointer? When I tried doing it I would receive the error:
new5.c:13:27: error: invalid operands to binary expression ('Car' (aka 'struct Car') and 'void *')
Which I think may be related to using the NULL
in the my_cars
array to signal the end of it, but wasn't positive. Additionally, is using NULL
in a non-char array a common way to show that the end has been reached? Where else could this be improved?
print_cars
andprint_cars2
(print_cars2 doesn't exist in the above). \$\endgroup\$