Arrays of arbitrary lengths
This example shows how to construct arrays of arbitrary lengths using pointers.
Source Code:
(main.c)
#include <stdio.h>
int main(){
int *p; /* declare a pointer to an integer */
int i;
p=(int *)malloc(sizeof(int)); /* Allocate a block of memory the size of an
integer and make p point to that block */
*p=4; /* Store 4 in that block */
printf("*p+1 = %d\n", (*p)+1);
free(p); /* free the memory allocated to p */
/* Warning: If you don't free memory after you are done using the space,
you will eventually use up all the memory available to your program. */
p=(int *)malloc(7*sizeof(int)); /* Allocate a block 7 times the size of an
integer. The pointer p points to the
first integer in that block. */
for (i=0; i<7; i++)
p[i]=2*i+1; /* Store 2*i+1 in the (i-1)th space in the block */
for (i=0; i<7; i++)
printf("p[%d]=%d ",i,p[i]); /* Print the array. */
printf("\n");
/* There are two equivalent ways to access each element
p[i] = *(p+i) */
for (i=0; i<7; i++)
printf("*(p+%d)=%d ",i,*(p+i)); /* Print the array. */
printf("\n");
p=(int *)realloc(p,9*sizeof(int)); /* Enlarge the array p points to. */
p[7]=7;
p[8]=8;
for (i=0; i<9; i++)
printf("p[%d]=%d ",i,p[i]); /* Print the array. */
printf("\n");
free(p); /* Again it is really bad to forget this */
return 0;
}
Output:
*p+1 = 5
p[0]=1 p[1]=3 p[2]=5 p[3]=7 p[4]=9 p[5]=11 p[6]=13
*(p+0)=1 *(p+1)=3 *(p+2)=5 *(p+3)=7 *(p+4)=9 *(p+5)=11 *(p+6)=13
p[0]=1 p[1]=3 p[2]=5 p[3]=7 p[4]=9 p[5]=11 p[6]=13 p[7]=7 p[8]=8
To compile: