C Programming Questions and Answers – Pointers and Addresses.c

The same question:
What will be the output of the following C code?

Question 1:

//   Date:2020/3/29
//   Author:xiezhg5
#include <stdio.h>
int main(void)
{
	int k=5;
	int *p=&k;
	int **m=&p;
	printf("%d %d %d\n",k,*p,**m);
	return 0;
}

//Answer:5 5 5 

Question 2:

//   Date:2020/3/29
//   Author:xiezhg5
#include <stdio.h>
int main(void)
{
	int k=5;
	int *p=&k;
	int **m=&p;
	**m=6;
	printf("%d\n",k);
	return 0;
}

//Answer: 6

Question 3:

//   Date:2020/3/29
//   Author:xiezhg5
#include <stdio.h>
int main(void)
{
	int a[3]={1,2,3};
	int *p=a;
	int **r=&p;
	printf("%p\n%p",*r,a);
	return 0;
}

//Answer:Same address is printed

Question 4:

//   Date:2020/3/29
//   Author:xiezhg5
#include <stdio.h>
int main(void)
{
	int a=1,b=2,c=3;
	int *p1=&a,*p2=&b,*p3=&c;
	int **ptr=&p1;
	*ptr=p2;
	printf("%d\n%d",p1,&b);
	return 0;
}

//Answer: p1->b

Pointer is a type of an object that refers to a function or an object of another type, possibly adding qualifiers. Pointer may also refer to nothing, which is indicated by the special null pointer value.
Notes:
Although any pointer to object can be cast to pointer to object of a different type, dereferencing a pointer to the type different from the declared type of the object is almost always undefined behavior. See strict aliasing for details.

It is possible to indicate to a function that accesses objects through pointers that those pointers do not alias.
See restrict for details.
(since C99)

lvalue expressions of array type, when used in most contexts, undergo an implicit conversion to the pointer to the first element of the array. See array for details.

char *str = "abc"; // "abc" is a char[4] array, str is a pointer to 'a'

Pointers to char are often used to represent strings. To represent a valid byte string, a pointer must be pointing at a char that is an element of an array of char, and there must be a char with the value zero at some index greater or equal to the index of the element referenced by the pointer.

***Reference:***https://en.cppreference.com/w/c/language/pointer

发布了131 篇原创文章 · 获赞 94 · 访问量 2932

猜你喜欢

转载自blog.csdn.net/qq_45645641/article/details/105181727