CSE109 Week8.2
CSE109 Week8.2
Lecture: 19
Reference Book: Teach yourself C (3rd Ed.)
Chapter/Section: A.4
#include <stdlib.h>
void *malloc(size_t size);
#include <stdlib.h>
void free(void *ptr);
int main(void) {
char *str[100];
for (int i = 0; i < 100; ++i) {
if ((str[i] = malloc(128)) == NULL) {
printf("Allocation error - aborting.\n");
exit(0);
}
gets(str[i]);
}
a = malloc(n * sizeof(int));
} }
printf("\n");
}
for (int i = 0; i < row; ++i) {
mat[i] = malloc(col * sizeof(int));
for (int i = 0; i < row; ++i) free(mat[i]);
if (mat[i] == NULL) {
free(mat);
printf("Could not allocate
}
memory.");
exit(0);
}
Recap: Pointer to struct
typedef struct point {
float x;
Point* midPoint(Point* point1, Point*
float y; point2)
} Point; {
Point* result = malloc(sizeof(Point));
Point* midPoint(Point* point1, Point* result->x = (point1->x+point2->x)/2;
point2); result->y = (point1->y+point2->y)/2;
return result;
int main(void) }
{
Point P, Q, *M;
scanf("%f %f",&P.x,&P.y);
scanf("%f %f",&Q.x,&Q.y);
M = midPoint(&P,&Q);
printf("%f %f",M->x,M->y);
return 0;
}
Using malloc to Allocate Storage for a struct
typedef struct point {
float x;
Point midPoint(Point* point1, Point* point2)
float y;
{
} Point;
Point result;
result.x = (point1->x+point2->x)/2;
Point midPoint(Point* point1, Point* point2); result.y = (point1->y+point2->y)/2;
return result;
int main(void) }
{
Point P, Q, M;
scanf("%f %f",&P.x,&P.y);
scanf("%f %f",&Q.x,&Q.y);
M = midPoint(&P,&Q);
printf("%f %f",M.x,M.y);
free(M);
return 0;
}
Calloc
#include <stdlib.h>
void *calloc(size_t num, size_t size);
#include <stdlib.h>
void *realloc(void *ptr, size_t size);
int main() {
0x1f772a0
(nil)
int *p = malloc(0);
printf("%p\n", p);
int *q = malloc(-1);
printf("%p\n", q);
return 0;
}