Presentation is loading. Please wait.

Presentation is loading. Please wait.

One-dimensional arrays and strings: Chapter 6, Slide 1 The concept of array - an extension of the basic model of memory:

Similar presentations


Presentation on theme: "One-dimensional arrays and strings: Chapter 6, Slide 1 The concept of array - an extension of the basic model of memory:"— Presentation transcript:

1 One-dimensional arrays and strings: Chapter 6, Slide 1 The concept of array - an extension of the basic model of memory:

2 Chapter 6, Slide 2 Accessing one-dimensional array via a pointer:

3 Chapter 6, Slide 3 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.

4 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; }

5 Chapter 6, Slide 6 The program displays: 0 1 12 13 14 15

6 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;

7 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");

8 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; }

9 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");

10 Chapter 6, Slide 10 In C++ we can overload operator [] and create “arrays” with range checking: chapter6_1chapter6_1 End of slides for chapter 6


Download ppt "One-dimensional arrays and strings: Chapter 6, Slide 1 The concept of array - an extension of the basic model of memory:"

Similar presentations


Ads by Google