Skip to content

Instantly share code, notes, and snippets.

@robwhess
Last active October 16, 2024 21:43
Show Gist options
  • Save robwhess/5b102e5f7dbaad3f51b48cd7ef9ac7a5 to your computer and use it in GitHub Desktop.
Save robwhess/5b102e5f7dbaad3f51b48cd7ef9ac7a5 to your computer and use it in GitHub Desktop.
CS 261 Week 3 Recitation Exercise
#include <stdlib.h>
int multiply_by_2(int* p) {
*p = *p * 2;
return *p;
}
int main() {
int n = 10, x = 16, y = 32, z = 64;
int* p1 = &x;
int* a = malloc(n * sizeof(int));
int* p2;
for (int i = 0; i < n; i++) {
a[i] = i;
}
p2 = a + (n / 2);
*p2 = 0;
z = multiply_by_2(&x);
y = multiply_by_2(p1);
free(a);
}
#include <stdlib.h>
struct product {
char* name;
float price;
};
struct product* create_product(char* name, float price) {
struct product* p = malloc(sizeof(struct product));
p->name = malloc((1 + strlen(name)) * sizeof(char));
strcpy(p->name, name);
p->price = price;
return p;
}
int main() {
int i, n = 5;
struct product** products = malloc(n * sizeof(struct product*));
for (i = 0; i < n; i++) {
products[i] = create_product("A product name", 32.99);
}
for (i = 0; i < n; i++) {
free(products[i]);
}
free(products);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment