当前位置:网站首页>My C language learning record (blue bridge) -- under the pointer
My C language learning record (blue bridge) -- under the pointer
2022-07-06 02:50:00 【Someone -jojo】
How strings are referenced
stay C In the program , Strings are stored in character arrays . Want to reference a string , You can use the following two ways .
1. Storing a string with a character array , You can refer to a character in a string by array name and subscript , It can also be declared by array name and format “%s” Output this character .
example : Defines an array of characters , Store string in it “I love Shiyanlou!”, Output the string and the 10 Characters .
establish 11-1.c File and enter the following code :
#include<stdio.h>
int main(){
char string[]="I love Shiyanlou!";
printf("%s\n",string);
printf("%c\n",string[9]);
return 0;
}
Enter the following command to compile and run :
gcc -o 11-1 11-1.c
./11-1
The program runs as follows :
Program analysis :
When defining a character array string The length is not specified , Because it is initialized , So its length is certain , The length should be 18, among 17 Byte storage “I love Shiyanlou!” this 17 Characters ( Contains spaces and exclamation marks ), The last byte stores the string '\0'
, Array name string Represents the address of the first element of the word array .
2. Point to a string constant with a character pointer variable , Referencing string constants with character pointer variables .
It is required to output a string through the character pointer variable .
Write the source program 11-2.c:
#include<stdio.h>
int main(){
char * string="I love Shiyanlou!";
printf("%s\n",string);
return 0;
}
The program runs as follows :
Program analysis :
For character pointer variables string initialization , In fact, it assigns the address of the first element of the string to the pointer variable string, send string Points to the first character of the string . Some people mistakenly think string Is a string variable , Think in the definition of “I love Shiyanlou!” These characters are assigned to the string variable , It's not right . stay C Only character variables in language , No string variable .
The following sentence printf("%s\n",string);
in %s Is the format used when outputting strings , Give character pointer variable name in output item string, Then the system will output string The first character of the string pointed to , And then automatically string Add 1, Make it point to the next character , Output the character again ... So until the end of string flag is encountered '\0'
, Therefore, re output can determine when the output character ends .
The string a Copy as string b, Then output the string b.
Their thinking :
Define two character array a and b, use “I am a programmer” Yes a Array to initialize . take a The characters in the array are copied one by one to b Array . You can reference and output character array elements in different ways , In this example, we use the address to find the value of each element . By changing the value of the pointer variable, it points to different characters in the string .
Programming 11-3.c use i++ To traverse the array , Program 11-4.c use p++ Traversal array .
Write the source program 11-3.c:
#include<stdio.h>
int main(){
char a[] = "I am a programmer",b[20];
int i;
for(i=0;*(a+i)!='\0';i++)
*(b+i) = *(a+i);
*(b+i) = '\0';
printf("string a is:%s\n",a);
printf("string b is:");
for(i=0;b[i]!='\0';i++)
printf("%c",b[i]);
printf("\n");
return 0;
}
Write the source program 11-4.c:
#include<stdio.h>
int main(){
char a[] = "I am a programmer",b[20],*p1,*p2;
p1 = a,p2 = b;
for(;*p1!='\0';p1++,p2++)
*p2 = *p1;
*p2 = '\0';
printf("string a is:%s\n",a);
printf("string b is:%s\n",b);
return 0;
}
Run two programs , The program runs as follows :
It can be seen that , The result is the same .
Character pointer as function parameter
Suppose you want to convert a string from a function “ Pass on ” To another function , You can pass it by address , That is, use the character array name as the parameter , You can also use character pointer variables as parameters . The contents of the string can be changed in the called function , The changed string can be referenced in the main function . Copy the string in the function call .
Their thinking :
Define a function copy_string
Used to realize the function of string replication , This function is called in the main function , The formal and actual parameters of a function can be character array names or character pointer variables, respectively . Program separately , For analysis and comparison .
Programming 11-5.c Using character array names as function parameters , Program 11-6.c Using character pointer variables as arguments , Program 11-7.c Using character pointer variable as parameter and actual parameter .
Write the source program 11-5.c:
#include<stdio.h>
int main(){
void copy_string(char from[],char to[]);
char a[] = "I am a teacher";
char b[] = "You are a programmer";
printf("string a=%s\nstring b=%s\n",a,b);
printf("copy string a to string b:\n");
copy_string(a,b);
printf("\nstring a=%s\nstring b=%s\n",a,b);
return 0;
}
void copy_string(char from[],char to[]){
int i = 0;
while(from[i]!='\0'){
to[i] = from[i];
i++;
}
to[i] = '\0';
}
Write the source program 11-6.c:
#include<stdio.h>
int main(){
void copy_string(char from[],char to[]);
char a[] = "I am a teacher";
char b[] = "You are a programmer";
char *from = a,*to = b;
printf("string a=%s\nstring b=%s\n",a,b);
printf("copy string a to string b:\n");
copy_string(from,to);
printf("\n string a=%s\n string b=%s\n",a,b);
return 0;
}
void copy_string(char from[],char to[]){
int i = 0;
while(from[i]!='\0')
{
to[i] = from[i];
i++;
}
to[i] = '\0';
}
Write the source program 11-7.c:
#include<stdio.h>
int main(){
void copy_string(char *from,char *to);
char *a = "I am a teacher";
char b[] = "You are a programmer";
char *p = b;
printf("string a=%s\nstring b=%s\n",a,b);
printf("copy string a to string b:\n");
copy_string(a,p);
printf("\n string a=%s\n string b=%s\n",a,b);
return 0;
}
void copy_string(char *from,char *to){
for(;*from!='\0';from++,to++)
*to = *from;
*to = '\0';
}
Run three programs , The program runs as follows :
It can be seen that , The result is the same .
Program analysis
- Program 11-5.c. Will array a Copy to array b after , Failed to cover all b The original contents of the array .b At the end of the array 3 Elements remain intact . At output b Due to pressing %s Output , encounter
'\0'
Will be over , So the first one'\0'
The following characters are not output .
2. Program 11-6.c.copy_string
unchanged , stay main
Function to define character pointer variables from and to, Point to two character arrays respectively a and b. Pointer to the variable from The value of is a Address of the first element of the array , Pointer to the variable to The value of is b Address of the first element of the array . As arguments , hold a The address and of the first element of the array b The address of the first element of the array is passed to the shape parameter group name from and to( They are also pointer variables in essence ).
3. Program 11-7.c. The formal parameter is changed to char * Type variable ( That is, character pointer variable ). In procedure (1) and (2) in copy_string
The parameters of the function use character array names , In fact, the compilation system treats character array names as pointer variables , It's just in different forms .
Comparison between character pointer variable and character array
Character arrays and character pointer variables can be used to store and operate strings , But there are differences between them , Mainly for the following :
- A character array consists of several elements , Put one character in each element , The address is stored in the character pointer variable ( String number 1 A character address ), Never put a string in a character pointer variable .
- Assignment method . You can assign values to character pointer variables , But you cannot assign values to array names . Assign values to character pointer variables :
char *a;
a = "I love shiyanlou!"; // Assign the address of the first element of the string to the pointer variable , legal . But to a Is not a string , Just the address of the first element of a string .
You cannot assign a value to a character array name in the following way :
char str[14];
str[0] = 'I'; // legal , Assign a value to a character array element
str = "I love Shiyanou"; // illegal , The array name is the address , Is a constant , Cannot be assigned
- The contents of the storage unit . Allocate several storage units for the character array at compile time , To store the values of each element , And for character pointer variables , Allocate only one storage unit .
Because there are too many contents introduced in the chapter of pointer , The concept and application are complex , Let's summarize , I hope you can clarify your thoughts .
- First of all, we should accurately understand the meaning of the pointer . The pointer is the address , Whenever there is “ The pointer ” The place of , Both can be used. “ Address ” Instead of , for example , The pointer to a variable is the address of the variable , A pointer variable is an address variable . To distinguish The pointer and Pointer to the variable . The pointer is the address itself , for example 2008 Is the address of a variable ,2008 Is the pointer to the variable . Pointer variables are variables used to store addresses .
- What is pointing ? Address means pointing to , Because the object with the address can be found through the address . For pointer variables , Whose address is stored in the pointer variable , Just say who this pointer variable points to . But it should be noted that : Not all types of data can be stored in the same pointer variable . for example :
- int a,*p;
- float b;
- p = &a; //a yes int type , legal
- p = &b; //b yes float type , Type mismatch
- Pointer arithmetic :
Pointer variable plus ( reduce ) An integer . for example :p++,p- -,p+i,p-i,p-=i And so on are pointer variables plus or minus an integer . The original value of the pointer variable ( Address ) Add to the number of bytes in the storage unit occupied by the variable it points to ( reduce ).
Pointer variable assignment . Assign a variable address to a pointer variable . for example :
p = &a; // Put the variable a Address assigned to p
p = &array; // Will array array Address assigned to p( here p Point to the entire array , The value of this address and the value of the first element of the array are actually the same , But the meaning is different , You can try printing (&array + 1) and (array + 1) Take a look at the value of )
p = array; // Will array array The address of the first element of is assigned to p
p = &a[0]; // Will array array The address of the first element of is assigned to p
p = &array[i]; // Will array array Of the i The address of each element is assigned to p
p = max; //max For defined functions , take max The entry address of is assigned to p
p1 = p2; //p1 and p2 Is a pointer variable with the same base type , take p2 The value is assigned to p1
Ben C Language tutorials are introductory tutorials , We just learn the basic concept and preliminary application of pointer , If you want to master it deeply and skillfully, you need to learn more deeply . Using pointers has two advantages :
- Improve programming efficiency
- When calling a function, when the value of the pointer to the variable changes , These values can be used for the main function , That is, you can get more changeable values from function calls
Pointer is very flexible , For skilled programmers , It can be used to write high-quality programs , Realize many functions that are difficult to realize in other high-level languages . But it is also very easy to make mistakes , And this kind of mistake is very hidden , So we need to be cautious when using pointers , More computer debugging .
Homework
Exercises 1
Write a program , Enter the month number , Output the English name of the month number . For example, the input 8, The output “August”, Requires pointer array processing .
Exercise 2
Yes n A circle of individuals , Sequence number . Count from the first person ( from 1 To report for duty 3), Always check in 3 Of the people out of the circle , The last one left is the one with the original number .
Explain :
Exercises 1
#include<stdio.h>
int main()
{
int num;
scanf("%d",&num);
// Initialization month
const char *month[] = {"January","February","March","April","May","June","July","August","September","October","November","December"};
// Print the specified month
printf("%s",*(month+num-1));
return 0;
}
Exercise 2
#include <stdio.h>
#define N 128 // The number of
int main()
{
int a[N] = {0}, out = 0, num = 0, *p;
p = a;
while (1){ // Cycle count off
if(*p == 0){ // If not eliminated
if (out == (N - 1)) break; // If there is only one person left
num++; // Number off
num %= 3; // The maximum is 3, here we are 3 From 0 Start
if(num == 0) { // by 0( namely 3) out
*p = 1;
out++;}
}
p++;
if (p == a + N)
p = a; // Cycle to the next person
}
printf(" The number of the last remaining person is :%d", p + 1 - a);
}
Fix pointer usage errors
Introduce
We have a C Language program , But it always fails to work as expected and needs to be repaired .
Knowledge point
- Linux Next C Language programming
- C Language foundation
- C Program parameter input and processing
- C Language pointer
First, we download this one bug Source program :
wget https://labfile.oss.aliyuncs.com/courses/1585/test_pointer.c
This program is used to sort , The expected execution effect of the executable file generated after the correct program compilation is as follows :
# Run the compiled program
$ ./test
please enter 3 integer number:1 2 3
the order is :3,2,1
$ ./test 2 1 3
the order is :3,2,1
The program will be right 3 Integers are arranged in descending order , And you can read data from the keyboard and command line .
The goal is
- Please repair the source file directly /home/project/test_pointer.c Existing in BUG, Open the file after downloading “File→Open”;
- Repaired test_pointer.c You can compile and run in the environment , And the input and output meet the expected requirements .
Hint
Pay attention to the parameters of the function .
Please click... At the bottom of the document after completion Submit results See if you pass the challenge .
Refer to the answer
#include<stdio.h>
#include<stdlib.h>
void exchange(int * q1,int * q2,int * q3);
int main(int argc,char **argv){ // tips: main Functions should be able to receive parameters on the command line
int a, b, c;
int *p1, *p2, *p3;
if(argc == 1){
printf("please enter 3 integer number:");
scanf("%d%d%d", &a, &b, &c);
}
else if(argc == 4){ //tips: Here we need to read data from the command line , use scanf Only input from the keyboard
a = atoi(argv[1]);
b = atoi(argv[2]);
c = atoi(argv[3]);
}
else
return -1;
p1 = &a;
p2 = &b;
p3 = &c;
exchange(p1, p2, p3);
printf("the order is :%d,%d,%d\n",a,b,c);
return 0;
}
void exchange(int *q1,int *q2,int *q3){
void swap(int *pt1,int *pt2);
if(*q1<*q2)
swap(q1,q2);
if(*q1<*q3)
swap(q1,q3);
if(*q2<*q3)
swap(q2,q3);
}
void swap(int *p1,int *p2){
int temp;
temp = *p1;
*p1 = *p2;
*p2 = temp;
}
边栏推荐
- 2345文件粉碎,文件强力删除工具无捆绑纯净提取版
- 【若依(ruoyi)】设置主题样式
- Pat 1084 broken keyboard (20 points) string find
- RobotFramework入门(二)appUI自动化之app启动
- Function knowledge points
- 原型图设计
- tcpdump: no suitable device found
- Yyds dry inventory comparison of several database storage engines
- 纯Qt版中国象棋:实现双人对战、人机对战及网络对战
- 会员积分营销系统操作的时候怎样提升消费者的积极性?
猜你喜欢
My C language learning record (blue bridge) -- on the pointer
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 13
A copy can also produce flowers
CobaltStrike-4.4-K8修改版安装使用教程
Which ecology is better, such as Mi family, graffiti, hilink, zhiting, etc? Analysis of five mainstream smart brands
[Yunju entrepreneurial foundation notes] Chapter II entrepreneur test 9
XSS challenges绕过防护策略进行 XSS 注入
Redis delete policy
QT release exe software and modify exe application icon
[ruoyi] enable Mini navigation bar
随机推荐
[Digital IC manual tearing code] Verilog asynchronous reset synchronous release | topic | principle | design | simulation
Software design principles
C language - Blue Bridge Cup - promised score
2022.02.13
C语言sizeof和strlen的区别
Deeply analyze the chain 2+1 mode, and subvert the traditional thinking of selling goods?
A doctor's 22 years in Huawei
How to read excel, PDF and JSON files in R language?
Function knowledge points
My C language learning record (blue bridge) -- on the pointer
Communication between microservices
【 kubernets series】 a Literature Study on the Safe exposure Applications of kubernets Service
2345文件粉碎,文件强力删除工具无捆绑纯净提取版
Installation and use tutorial of cobaltstrike-4.4-k8 modified version
原型图设计
[Chongqing Guangdong education] higher mathematics I reference materials of Southwest Petroleum University
High number_ Vector algebra_ Unit vector_ Angle between vector and coordinate axis
Dachang image library
【Unity3D】GUI控件
Zhang Lijun: penetrating uncertainty depends on four "invariants"