Presentation is loading. Please wait.

Presentation is loading. Please wait.

Computer Science II CS132/601* Lecture #C-3.

Similar presentations


Presentation on theme: "Computer Science II CS132/601* Lecture #C-3."— Presentation transcript:

1 Computer Science II CS132/601* Lecture #C-3

2 pointer arrays char *b[5];
declare b as an array of 5 elements, with each element being a pointer to character. initialization: char *b[5]={“one”, “two”, “three”, “four”, “five”};

3 pointers vs multi-dimensional array
compare char a[5][6]; 30 character sized memory cells allocated char *b[5]; only an array of 5 pointers to character are allocated, and they are NOT initialized yet. char *b[5]={“one”, “two”, “three”, “four”, “five”}; each pointer in the array can point to different length array! memory allocated? (3+1)+(3+1)+(5+1)+(4+1)+(4+1) plus 5 cells of pointers char a[][6]={“one”, “two”, “three”, “four”, “five”}; 30 bytes

4 pointers to functions we can define a pointer to a function
it can be assigned it can be placed in arrays it can be passed to functions it can be returned by functions

5 example void Traverse(int s, void (*Visit)(int)) { …… (*Visit)(s); }
void v(int s) { printf("%d\n",s); How to call this function? Traverse(a, v);

6 memory allocation for variables
static allocation compiler allocates fixed memory to globally defined variables, which persist through the entire program. automatic allocation variables inside a function call is allocated in system stack, will be freed when function call returns dynamic allocation allocate memory in heap while program is running

7 dynamic memory allocation
void * malloc (int nBytes) //returns a generic pointer to the allocated memory space void fun1 () { …… char *cp; cp = malloc(10); } or cp = (char *) malloc(10); 10 bytes allocated in Heap cp Local memory Heap memory

8 dynamic memory allocation
good practice: always check if enough memory allocated by malloc() cp=malloc(10); if (cp==NULL) Error(“no memory available”); free that dynamically allocated memory once you are done with it. free(cp);

9 String basics String: a group of characters. Examples:
printf(“Average = %.2f”, avg); #define ERR_PREFIX “****Error – “ #define INSUFF_DATA “Insufficient Data”

10 Declaring and initializing string values
char string_var[30]; char str[20]=“Initial value”; char str[]=“hello!”; Null character: character ‘\0’ that marks the end of a string in C language. The characters followed by ‘\0’ will be ignored. However, ‘\0’ itself will occupy an element. Thus, the number of characters in a string is between 0 to one less than its declared size.

11 Array of strings #define NUM_PEOPLE 30 #define NAME_LEN 25 …
char names[NUM_PEOPLE][NAME_LEN]; char month[12][10] = {“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”};

12 Input/output printf(“Topic: %s\n”, string_val); Right-justified:
printf(“%10s\n”, string_val); Left-justified: printf(“%-10s\n”,string_val); scanf function can be used for input of a string. However, no ‘&’ symbol is needed.

13 String Input/Output with scanf and printf

14 Execution of scanf ("%s", dept);

15 Execution of scanf("%s%d%s%d", dept, &course_num, days, &time); on Entry of Invalid Data

16 String library functions
Wrong assignment operation: char one_str[20]; one_str = “Test string”; C language provides library functions for this purpose. strcpy, strncpy, strcat, strncat, strcmp, strlen and strtok.

17 String assignment strcpy(one_str, “Test String”);
strcpy(one_str, “A very long test string”); strncpy(one_str, “Test String”, 20); strncpy(one_str, “A very long test string”,20); The best way: strncpy(dest, source, dest_len-1); dest[dest_len-1] = ‘\0’;

18 Substrings Substring: a fragment of a longer string. Example:
char result[10], sl[15] = “Jan. 30, 1996”; strncpy(result, sl, 9); result[9] = ‘\0’; OR: strncpy(result, &sl[5], 2); result[2] = ‘\0’;

19 Execution of strncpy(result, s1, 9);

20 Execution of strncpy(result, &s1[5], 2);

21 Example char last[20], first[20], middle[20];
char pres[20]=“Adams ,John Quincy”; strncpy(last, pres, 5); last[5] = ‘\0’; strncpy(first, &pres[7], 4); first[4] = ‘\0’; strcpy(middle, &pres[12]);

22 Example (Cont.) char *last, *first, *middle;
char pres[20]=“Adams ,John Quincy”; char pres_copy[20]; strcpy(pres_copy, pres); last = strtok(pres_copy, “, “); first = strtok(NULL, “, “); middle = strtok(NULL, “, “);

23 Some other concepts String length: in a character array, the number of characters before the first null character. Empty string: a string of length zero: the first character of the string is the null character.

24 String concatenation Concatenation: joining of two strings.
Library functions: strcat and strncat. Example: #define STRSIZ 15 char f1[STRSIZ] = “John”, f2[STRSIZ] = “Jacqueline”, last[STRSIZ] = “Kennedy”; strcat(f1, last); strcat(f2, last); strncat(f2, last, 3);

25 #define STRSIZ 20 char s1[STRSIZ] = “Jupiter “, s2[STRSIZ] = “Symphony”; printf(“%d %d\n”, strlen(s1), strlen(strcat(s1, s2))); printf(“%s\n”, s1); if(strlen(s1) + strlen(s2) < STRSIZ) { strcat(s1, s2); } else { strncat(s1, s2, STRSIZ – strlen(s1) – 1); s1[STRSIZ-1] = ‘\0’;

26 Distinction between characters and strings
A type char value is used with ‘’, string “”. A type char value is not valid for a function with a corresponding parameter of type char *. Q \0 ? Character ‘Q’ String “Q” (represented by its initial address)

27 Scanning a full line Library functions: gets and fgets.
Like other functions: if the size of the input string is bigger than the maximal size allowed, it will cause overflow.

28 String comparison For char: crsr_or_frgt == ‘C’ ch1 < ch2
For string: str1 < str2 is a valid statement, but it determines the relationship of memory addresses not the values of strings. Library function: strcmp and strncmp.

29 Possible results of strcmp(str1, str2)
Relationship Value returned Example str1 is less than str2 negative integer str1 is “marigold” str2 is “tulip” str1 equals str2 zero str1 and str2 are both “end” str1 is greater than str2 positive integer str1 is “shrimp” str2 is “crab”

30 Executing strcpy (list [index_of_min], list[fill]);

31 An Array of Pointers

32

33

34

35 Arrays of string constants
char month[12][10] = {“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”}; char *month[12] = {“January”, “February”, “March”, “April”, “May”, “June”, “July”, “August”, “September”, “October”, “November”, “December”};

36 Character operations System functions used to deal with individual characters are defined in the header file: ctype.h. Input/output functions scanf(“%c”, &ch) ch=getchar() getc(inp) putchar(‘a’) putc(‘a’,outp)

37

38 Character analysis and conversion
isalpha: if argument is a letter of the alphabet? isdigit: if argument is one of the ten decimal digits? islower(isupper): if argument is a lowercase (or uppercase) letter of the alphabet? ispunct: if argument is a punctuation character? isspace: if argument is a whitespace character such as a space, a newline or a tab? tolower(toupper): convert character.

39 String Function for a Greater-Than Operator That Ignores Case

40 Structure type definition
In database, record: a collection of information about one data object. In C language, structure type: a data type for a record composed of multiple components.

41 Example Name: Jupiter Diameter: 142,800 km Moons: 16
Orbit time: 11.9yr Rotation time: 9.925hr. #define STRSIZE 10 typedef struct { char name[STRSIZ]; double diameter; int moons; double orbit_time; double rotation_time; } planet_t;

42 Declaration and initialization
{ planet_t current_planet, previous_planet, blank_planet={“”,0,0,0,0}; }

43 Hierarchical structure
A structure containing components that are structures. Example: typedef struct { double diameter; planet_t planets[9]; char galaxy[STRSIZ]; } solar_sys_t;

44 Syntax Typedef struct { type1 id_list1; type2 id_list2; …
typen id_listn; } struct_type;

45 Manipulation Manipulating individual components
Direct component selection operator: a period placed between a structure type variable and a component name to create a reference to the component. Manipulating whole structures previous_planet=current_planet;

46 Assigning Values to Components of Variable current_planet

47 Program style To avoid confusion:
for user-defined structures: we use the lowercase letters and end in the suffix _t for names.

48 Structures as input/output parameters
When a structured variable is passed as an input argument to a function, all of its component values are copied into the components of the function’s corresponding formal parameter. When a structure variable is passed as an output argument, the address-of operator must be applied in the same way that we would pass output arguments of the standard types char, int and double.

49 Function with a Structured Input Parameter

50 Function Comparing Two Structured Values for Equality

51 Function with a Structured Output Argument

52 Indirect component selection operator
The character sequence -> placed between a pointer variable and a component name creates a reference that follows the pointer to a structure and selects the component. Result=scanf(“%s%lf%d%lf%lf”, plnp->name, &plnp->diameter, &plnp->moons, &plnp->orbit_time, &plnp->rotation_time);

53 Data Areas of main and scan_planet during Execution of status = scan_planet (¤t_planet);

54 Function get_planet Returning a Structured Result Type

55 Function to Compute an Updated Time Value
Typedef struct { int hour, minute, second; } time_t;


Download ppt "Computer Science II CS132/601* Lecture #C-3."

Similar presentations


Ads by Google