如何回答关于恒指针这次采访的测试? [英] How to answer this interview test about constant pointers?

查看:139
本文介绍了如何回答关于恒指针这次采访的测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在其中他们问我这个问题的采访

 #包括LT&;&stdio.h中GT;
诠释的main()
{
INT * const的P = NULL;
INT常量* Q = NULL;
p ++;
q ++;
的printf(%d个\\ N,P);
的printf(%d个\\ N,Q);
}

如何将上述程序的行为

a)芘将增加4个字节;结果
  和Q也将增加4个字节;

二)p将为零结果
   那么Q值指向内存中提前4个字节;

c)出错会在上述程序

我无法理解有什么语句之间的区别

 为int * const的P = NULL;
INT常量* Q = NULL;


解决方案

为int * const的P = NULL;

P 恒指针为整数。指针是常数(指针值不能改变);整数指向不恒定(整数值可以被修改)。

所以语句:

 点++;

将无法编译,因为试图修改一个恒定值(指针)。

和语句:

 (* P)++;

将递增的整数值所指向的指针 P (但由于 P 分配 NULL ,将未定义行为


INT常量* Q = NULL;

是一个指向一个恒整数 .The指针不恒定(指针值可以改变);整数指向的常数(整型值不能被修改)。

所以语句:

 ①++;

将修改指针提前指向内存中的4个字节(假设的sizeof(INT) 4)。 (因为分配 NULL 为0x4 - 我以为NULL为零(这是真的在目前所有的实现),递增NULL指针实际上是不确定的行为

和语句:

 (* Q)++;

将无法编译,因为试图修改一个恒定值(整数指出,为常数)

I had an interview in which they had asked me this question

#include<stdio.h>
int main ()
{
int* const p=NULL;
int const *q=NULL;
p++;
q++;
printf("%d\n",p);
printf("%d\n",q);
}

How will above program behave

a) p will increment 4 bytes;
and q will also increment 4 bytes;

b) p will be zero
q will point to memory 4 bytes ahead;

c) error will come in above program

I am not able to understand what is the difference between the statements

int* const p=NULL;
int const *q=NULL;

解决方案

int* const p=NULL;

p is a constant-pointer to an integer. The pointer IS constant (the pointer value cannot be changed); the integer pointed to is not constant (the integer value can be modified).

So statement:

p++;

will fail to compile because trying to modify a constant value (the pointer).

and statement:

(*p)++;

will increment the integer value being pointed by pointer p (but because p is assigned NULL, it will be undefined behaviour)


int const *q=NULL;

q is a pointer to a constant-integer.The pointer is not constant (the pointer value can be changed); the integer pointed to IS constant (the integer value cannot be modified).

So statement:

q++;

will modify pointer q to point to memory 4 bytes ahead (assuming sizeof(int) is 4). (because q is assigned NULL, q will be 0x4 -- I assume NULL is zero (which is true in all current implementation), incrementing NULL pointer is actually undefined behaviour )

and statement:

(*q)++;

will fail to compile because trying to modify a constant value (the integer pointed to is a constant)

这篇关于如何回答关于恒指针这次采访的测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆