Pointers are typically the one thing people coming from Javaland struggle with when encountering C for the first time. If you come bottom up from assemblerland you are OK.
Here is our very pesky pointers quiz. We went over this in x-hour. You will get a marked up copy of your answer sheet back. We will grade it but it will have zero impact on your course grade. This is purely fun in a torturous sense of course!
This set of problems ask you to guess the execution results of C code. In this exercise, you will understand how C handle strings and how to write correct string processing code. Assume that:
char* p = "ABCDE";
|
for all questions.
printf("Print p: %s\n", p);
|
Answer: Print p: ABCDE
printf("Print p[1]: %c\n", p[1]);
|
Answer: Print p[1]: B
printf("Print *p+2: %c\n", *p+2);
|
Answer: Print *p+2: C
Following string questions are not mentioned today, but they are also important.
printf("Print p: %c\n", p);
|
Answer: Print p: (STRANGE RANDOM CHARACTERS)
printf("Print (p+1): %s\n", (p+1));
|
Answer: Print (p+1): BCDE
char c[30];
int i; for (i = 0; i < 5; i++) c[i] = p[i]; printf("%s\n", c); |
Answer: SEGMENT FAULT
We have the following intialization
int a[3]; a[0]=0; a[1]=1; a[2]=2;
int *b=a; short *c=a; |
for all questions in this section.
printf("%d\n", a);
|
Answer: A memory address, let’s just say x
printf("%d\n", *a);
|
Answer: 0
printf("%d\n", *(a+1));
|
Answer: 1
printf("%d\n", *(a+3));
|
Answer: Segementation fault
printf("%d\n", *a+1);
|
Answer: 1, but it is not like question 6!
printf("%d\n", b[2]);
|
Answer: 2
printf("%d\n", c[0]);
|
Answer: 0
We have the following initialization
int B[2][2];
B[0][0]=1; B[0][1]=2; B[1][0]=3; B[1][1]=4; |
for all questions in this section.
printf("%u\n", B);
|
Answer: x (A memory address, let’s say it is x)
printf("%u\n", &B[0][0]);
|
Answer: x
printf("%u\n", B[1]);
|
Answer: (x + 8)
printf("%u\n", *B[0]);
|
Answer: 1
int D[2][2] = B;
|
Answer: No. Compiling Error.
int D[][] = B;
|
Answer: No. Compiling Error.
int *D = B;
|
Answer: Yep.
When you want to declare a array and initialize it at the same time, the right way is to do as follows:
int D[2][2] = {{1, 2}, {3, 4}};
|
or:
int D[] = {1, 2, 3, 4};
|
int *D = B;
printf("%u\n", D[1][1]); |
Answer: No. Compiling Error.
int E[2][2][2];
printf("%u\n", E+1); |
Wei Pan: I welcome anyone come to discuss this quiz.
Following string questions are not mentioned today, but they are also important.
int *D = B;
printf("%u\n", D+2); |
Answer: x + 8
int *D = B;
printf("%u\n", *(D+2)); |
Answer: 3
This set of questions ask you to think about the value and equivalent expressions of an expression. You will need the similar skill in Lab 4.Suppose:
int a = 12;
int b = &a; int **c = &b; |
*b
|
Answer: a, 12
*c
|
Answer: b, &a
**c
|
Answer:a, 12
The following questions are also important, but they are not mentioned in class.
*(*c)
|
Answer: a, *b, 12