[Instructions] [Search] [Current] [News] [Syllabus] [Glance] [Links] [Handouts] [Outlines] [Labs] [Assignments] [Exams] [Examples] [Project]
Back to Pointers. On to Data-Link Basics.
Held Friday, February 11, 2000
Overview
Today, we conclude our study of C by visiting some further issues of memory management.
Notes
Contents
Summary
ip as a pointer to an integer,
ip[0] is the memory location associated with
ip.
ip[1] is the next memory location!
iarr as an array of integers,
*iarr gives the 0th element of the array
and iarr++ chops off the first element.
int iarr[10];
malloc.
malloc is declared in stdlib.h, which you
should include.
size_t) as a parameter. That's
the number of bytes to allocate.
void *).
free.
Consider the following program:
#include <stdio.h>
int *stuff;
/* "Allocate" space for stuff. */
void setupStuff()
{
int junk[10];
int i;
stuff = junk;
for (i = 0; i < 10; i++)
stuff[i] = i;
} /* setupStuff() */
/* Print some values */
void printVals()
{
int i,j,k;
j = 100;
k = 200;
for (i = 0; i < 10; i++)
printf("stuff[%d]: %d\n", i, stuff[i]);
printf("i: %d\n", i);
printf("j: %d\n", j);
printf("k: %d\n", k);
} /* printVals() */
main()
{
setupStuff();
printVals();
} /* main() */
gcc and then run it.
gcc -O and then run it.
gcc to determine what -O does.
cc and then run it.
c89 and then run it.
printVals recurses
five times. Compile with c89 and execute.
stuff = (int *) malloc(10*sizeof(int));
Consider the following program:
#include <stdio.h>
#include <stdlib.h>
#define ENTRIES 5
main()
{
int i;
int *A;
int *B;
int *C;
A = (int *) malloc(ENTRIES * sizeof(int));
B = A;
C = (int *) malloc(ENTRIES * sizeof(int));
for (i = 0; i < ENTRIES; i++) {
A[i] = i;
C[i] = i;
}
for (i = 0; i < ENTRIES; i++)
printf("B[%d]: %d; ", i, B[i]);
printf("\n");
for (i = 0; i < ENTRIES; i++)
printf("C[%d]: %d; ", i, C[i]);
printf("\n");
free(A);
A = malloc((ENTRIES-1) * sizeof(int));
for (i = 0; i < ENTRIES-1; i++)
A[i] = 9*i;
for (i = 0; i < ENTRIES; i++)
printf("B[%d]: %d; ", i, B[i]);
printf("\n");
for (i = 0; i < ENTRIES; i++)
printf("C[%d]: %d; ", i, C[i]);
printf("\n");
}
gcc and then run it.
Thursday, 20 January 2000
Friday, 11 February 2000
Back to Pointers. On to Data-Link Basics.
[Instructions] [Search] [Current] [News] [Syllabus] [Glance] [Links] [Handouts] [Outlines] [Labs] [Assignments] [Exams] [Examples] [Project]
Disclaimer Often, these pages were created "on the fly" with little, if any, proofreading. Any or all of the information on the pages may be incorrect. Please contact me if you notice errors.
This page may be found at http://www.math.grin.edu/~rebelsky/Courses/CS364/2000S/Outlines/outline.09.html
Source text last modified Mon Feb 14 12:46:58 2000.
This page generated on Mon Feb 14 12:52:15 2000 by Siteweaver. Validate this page's HTML.
Contact our webmaster at rebelsky@grinnell.edu