C
Adding products
Write the function that adds products to the cart.
The cart_add function
In this lesson we'll write the cart_add function. It adds a new item to the cart and increments cart_size.
void cart_add(const char *name, double price, int qty) {
if (cart_size >= MAX_ITEMS) return;
strcpy(cart[cart_size].name, name);
cart[cart_size].price = price;
cart[cart_size].qty = qty;
cart_size++;
}
strcpy copies the string; cart_size points to the next free slot. If the cart is full, we return early. This safety check prevents overflow.
Copying strings with strcpy
In C you can't assign strings with =; you must use strcpy. strcpy copies a string into a destination array character by character.
char name[32];
strcpy(name, "Apple"); // name is now "Apple"
That's why we use strcpy(cart[cart_size].name, name) inside cart_add. It's declared in the string.h header. To prevent overflow, strncpy can be preferred.
Exercise Add two items
Write the cart_add function: void cart_add(const char *name, double price, int qty). If the cart is full (cart_size >= MAX_ITEMS) return early. Copy the name with strcpy, set price and qty, then cart_size++. main already adds two items; just complete the function. Expected output: 2 items added.
Show example solution
#include <stdio.h>
#include <string.h>
#define MAX_ITEMS 10
struct CartItem {
char name[32];
double price;
int qty;
};
struct CartItem cart[MAX_ITEMS];
int cart_size = 0;
void cart_add(const char *name, double price, int qty) {
if (cart_size >= MAX_ITEMS) return;
strcpy(cart[cart_size].name, name);
cart[cart_size].price = price;
cart[cart_size].qty = qty;
cart_size++;
}
int main(void) {
cart_add("Apple", 2.50, 3);
cart_add("Bread", 5.00, 1);
printf("%d items added\n", cart_size);
return 0;
}
Test yourself
-
Increment cart_size
void cart_add(const char *name, double price, int qty) {
if (cart_size >= MAX_ITEMS) return;
strcpy(cart[cart_size].name, name);
cart[cart_size].price = price;
cart[cart_size].qty = qty;
____;
}
Show answer
void cart_add(const char *name, double price, int qty) {
if (cart_size >= MAX_ITEMS) return;
strcpy(cart[cart_size].name, name);
cart[cart_size].price = price;
cart[cart_size].qty = qty;
cart_size++;
}
-
What's cart_size after cart_add?
cart_add("Apple", 2.50, 3);
cart_add("Bread", 5.00, 1);
Show answer
2 — After two adds cart_size = 2.
-
Match the add pieces
- strcpy
- Copies a string
- cart_size++
- Increments count
- MAX_ITEMS
- Upper bound
- void cart_add
- Function signature
Next lesson: Calculating totals