1.指针基础
int i = 5;
int *p = &i;
题目的意思就是哪个表达式可以和i等效替换。
& 是取地址运算符, 是一元运算符,返回操作数的内存地址.
* 是间接寻址运算符,是一元运算符,返回操作数所指定地址的变量的值.
(a) √
(b) &p 是取 p的地址,并不是 i. ×
(c) &p 的基础上,再加上 * 就得到 i 的地址. ×
(d) *p等于i, &*p 是取 i 的地址. ×
(e) 语法错误. ×
(f) 取i的地址. ×
(g) i的值,5. ×
(h) 语法错误. ×
验证:
int main(void)
{
int i = 5;
int* p;
p = &i;
printf("&i = %d\n", &i); //&i = 12254360
printf("&p = %d\n", &p); //&p = 12254348
printf("*p = %d\n", *p); //*p = 5
printf("*&p = %d\n", *&p); //*&p = 12254360
printf("&*p = %d\n", &*p); //&*p = 12254360
printf("*&i = %d\n", *&i); //*&i = 5
// &p = 2; Syntax Error. //赋值运算符左侧需要是左值
// &*p = 2; Syntax Error. //赋值运算符左侧需要是[左值](https://blog.csdn.net/weixin_44175439/article/details/118441351)
// *i = 5; Syntax Error. //*的操作数必需要是指针(即地址.这里要和指针变量区分开)
*&i = 3;
printf("i = %d\n", i); //i = 3
}
(a)应该把地址赋给指针变量,所以应该是p = &i
(b)不是赋值.
(c)语法错误.
(d)语法错误.
(f) 正确.此时p和q指向同一个地址.
(g)语法错误.p是int *型的,而*q是int型的.
(h)语法错误.
(i)正确.此时p和q指向同一个地址.
答案:
void avg_sum(float a[], int n, float* avg, float* sum)
{
int i;
*sum = 0.0;
for (i = 0; i < n; i++)
{
*sum += a[i];
}
*avg = *sum / n;
}
int main(void)
{
float avg;
float sum;
float a[] = { 1, 2, 3 };
avg_sum(a, 3, &avg, &sum);
printf("avg = %f\n", avg);
printf("sum = %f\n", sum);
}
答案:
void swap(int* p, int* q)
{
int tmp;
tmp = *p;
*p = *q;
*q = tmp;
}
答案:
void find_two_largest(int a[], int n, int* largest, int* second_largest)
{
int i = 0;
*largest = 0;
*second_largest = 0;
for (; i < n; i++)
{
if (a[i] > *largest)
{
*second_largest = *largest;
*largest = a[i];
}
}
}
答案:
int* find_middle(int a[], int n)
{
return &a[n / 2];
}
未完,待续…