In: Computer Science
FOR C PROGRAMMING LANGUAGE
Draw the main memory diagram as captured at the end of the C program (i.e. return 0; statement). Your diagram must clearly shows where str, p1, p2, and p3 are pointing to, when the program terminates.
int main(void) {
char str[] = "cs111 NYU"; char* p1 = str;
p1 ++;
char** p2 = &p1;
char* p3 = &str[4];
printf("1. str = %s\n", p1); if(p3 - p1 == 4) {
printf("2. p1 == p3\n"); }
printf("3. char1 %c, char2 %c\n", *(*p2 + 2) + 1, *(*p2 + 2 + 1));
return 0; }
Here is the full memory diagram of above program --->
number written below any box tells address of that memory block in main memory and value in the box tells value stored at that memory address in main memory.
Char *p1 = str; // p1 = 2000
p1
2000 |
5000
p1++;
p1 *p1 = ‘s’
2001 |
5000
Char *p2 = &p1;
p2
5000 |
7000
p3 = &str[4];
p3 *p3 = ‘1’
2004 |
8000
clearly p3-p1 ===2004-2001 = 3
*p2 = 2000
*p2+2 = 2002
*(p2+2) +1= ‘1’+1 = ‘2’
*(*p2+2+1) = value at address 2003 which is 1
output of program
1. str = s111 NYU
3. char1 2, char2 1