当前位置:网站首页>Pointer - character pointer

Pointer - character pointer

2022-07-06 00:18:00 It's Yi'an

Part1:

Array function parameter Character pointer Basic usage Constant string

When we pass an array into a function , In fact, what is passed in is an address , Modify the content in the address , On the sizeof What you get is not the space occupied by the array , It's the space occupied by the pointer .

#include<stdio.h>

void mylen(int arr[]) {
	int sz = sizeof(arr) / sizeof(arr[0]);
	printf("%d", sz);
}
int main(void) {
	int arr[10] = { 0 };
	mylen(arr);

	return 0;
}

// The result is 1/2

Character pointer : We usually define a character first a, Define a character pointer variable to point to a.

char test='a';
char* p=&test;

Or define a character array , Define a pointer variable to point to it .

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

If we define a pointer variable directly , Then assign a character or string to the pointer variable , In fact, it is the address of the first character . Such a string is called a constant string .

char* p="abcdef";

Why is it called a constant string ? According to our previous understanding , We have a pointer to the first character. Can we modify it ?

#include<stdio.h>

int main(void) {
	char* p = "abcdef";
	*p = 'W';
	printf("%s", p);
}

The program running here will crash . But the compiler does not report an error , To solve this problem , We can add const

const char* p="abcdef";

Part2:

Common mistakes Compare character arrays Constant space

We often encounter the judgment condition of comparing two arrays when we are doing problems , At this time, if you directly compare array names , That's actually comparing addresses .

    char arr[] = "abcdef";
	char arr1[] = "abcdef";
	if(arr==arr1)// The address is different 

Constant string , If two constant strings are the same , Then the system will not open up two spaces for storage , At this time, if you point to it with two pointers , Its storage address is the same .

	char* p = "abcdef";
	char* q = "abcdef";
	if(p==q)// Because constants are the same ,p And q The value of is the same 

原网站

版权声明
本文为[It's Yi'an]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/02/202202140232467862.html