C language--pointer advanced 1--character pointer

There is a character pointer type among pointer types: char*

General use of char*

char ch = 'a';
char* pc = &ch; // pc就是字符指针 存放char类型变量的地址
*p = 'w'; // 通过指针解引用访问/修改ch

Pointer to string

char arr[] = "abcdef";
char* p = arr;

The array name is the address of the first element of the array. p stores not the array arr itself, but its first address. The string is continuous, and with its first address, all its contents can be accessed.

Execute the following statement

printf("%c\n", *p);
printf("%s\n", p);

result:

What is found when dereferencing p is the first element a of the array, that is, *p is equivalent to arr[0]; printing p through the %s format means printing the string pointed to by p.

Pointer to string constant

char* p = "abcdef";

p points to a constant string "abcdef", and the content of the string can still be printed through p.

A constant string cannot be modified, and it cannot be modified through a pointer to it. If a character pointer points to a constant string, it should be modified with const to avoid modification of the string.

const char* p = "abcdef";

an interview question

What is the output of the following program?

#include <stdio.h>
int main()
{
	char str1[] = "hello bit.";
	char str2[] = "hello bit.";
	const char* str3 = "hello bit.";
	const char* str4 = "hello bit.";
	if (str1 == str2)
		printf("str1 and str2 are same\n");
	else
		printf("str1 and str2 are not same\n");

	if (str3 == str4)
		printf("str3 and str4 are same\n");
	else
		printf("str3 and str4 are not same\n");

	return 0;
}

Answer:

analyze:

str1 and str2 are two arrays. They each have a memory space. Even if their contents are the same, they will not share the same memory because they are two different variables and their contents can be modified at any time. str1 and str2 are not the same.

str3 and str4 each point to a constant string. Constant strings cannot be modified, so str3 and str4 can point to the same memory. str3 and str4 are the same.

Note that pointer variables store addresses. To compare two pointer variables is to compare their contents, that is, the addresses where they are stored.

Continue to learn advanced pointer content, see the next article: Pointer Array

Supongo que te gusta

Origin blog.csdn.net/2301_79391308/article/details/132915340
Recomendado
Clasificación