Mem 6
Mem 6
Chapter 6, Slide 1
Accessing one-dimensional array via a pointer:
Chapter 6, Slide 2
Representation of the int x[6] array:
const
int* x x[0] x[1] x[2] x[3] x[4] x[5]
*(x+0) *(x+1) *(x+2) *(x+3) *(x+4) *(x+5)
Chapter 6, Slide 3
void doit(int y[])
{
y[0] = 0;
y[1] = 1;
}
int main()
{
int i;
int x[6]={10,11,12,13,14,15};
doit(x);
for(i = 0; i < 6; i++)
printf("%d ",x[i]);
putchar('\n');
return 0;
}
Chapter 6, Slide 5
The program displays: 0 1 12 13 14 15
80804048 0 1 12 13 14 15
int* x x[0] x[1] x[2] x[3] x[4] x[5]
y[0] y[1]
doit() activation frame
80804048
int* y
Chapter 6, Slide 6
Dynamic one-dimensional arrays is simple:
int main()
{
int i;
int* x;
x = malloc(6*sizeof(int));
if (x == NULL) exit(1);
x[0] = 10;
x[1] = 11;
x[2] = 12;
x[3] = 13;
x[4] = 14;
x[5] = 15;
Chapter 6, Slide 7
for(i = 0; i < 6; i++)
printf("%d ",x[i]);
putchar('\n');
return 0;
}
Chapter 6, Slide 7
as well as in a dynamic array
char* x;
x = malloc(30);
strcpy(x,"hello");
Chapter 6, Slide 8
Missing NULL could spell big troubles (see overflows).
p = malloc(5);
strcpy(p,"hello");
Chapter 6, Slide 9
In C++ we can overload operator [] and create “arrays” with
range checking: chapter6_1
Chapter 6, Slide 10