One-dimensional arrays and strings:
Chapter 6, Slide 1
itemwith
index 0
itemwith
index 1
itemwith
index 2
itemwith
index 3
The concept of array - an extension of the basic model of memory:
Chapter 6, Slide 2
Accessing one-dimensional array via a pointer:
itemwith
index 0*p
itemwith
index 1*(p+1)
itemwith
index 2*(p+2)
itemwith
index 3*(p+3)
p
Chapter 6, Slide 3
constint* x x[0]
*(x+0)x[1]
*(x+1)x[2]
*(x+2)x[3]
*(x+3)x[4]
*(x+4)x[5]
*(x+5)
Representation of the int x[6] array:
• The size of the array is “forgotten” (after passing it to a function), no index range run-time testing is possible.
• Arrays passed by reference, as the pointer representing it is passed by value.
Chapter 6, Slide 5
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 6
80804048
int* x x[0]y[0]
0 1 12 13 14 15
x[1]y[1]
x[2] x[3] x[4] x[5]
address80804048
address80804052
address80804056
address80804060
address80804064
address80804070
doit() activation frame
80804048
int* y
The program displays: 0 1 12 13 14 15
Chapter 6, Slide 7
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;}
Strings are char arrays terminated by NULL '\0'
Thus a string can be stored in a static array:
char x[30] = "hello";or char x[30]; strcpy(x,"hello");
Chapter 6, Slide 8
as well as in a dynamic array
char* x;x = malloc(30);strcpy(x,"hello");
Thus a string is represented by a pointer and passed by reference.
char* strcpy(char* dest,const char* src){ char *dest1 = dest; while((*dest++=*src++) != NULL); return dest1;}
Chapter 6, Slide 9
Missing NULL could spell big troubles (see overflows).
Not allocating memory for a string is the most common error (leading to erratic behaviour):
int main(){ char* p; strcpy(p,"hello"); return 0;}
Insufficient memory could spell troubles (overflows):
p = malloc(5); strcpy(p,"hello");
Chapter 6, Slide 10
In C++ we can overload operator [] and create “arrays” with range checking: chapter6_1
End of slides for chapter 6