Idea analysis
Supplementary knowledge points
1. In C language, the array name of a one-dimensional array is actually a pointer to the first element of the array.
2. If the pointer p already points to a character string, to judge whether the character string is over, generally use the method of while(*p!='\0').
Take the printout arr[30]="hello world"; as an example to explain.
We print the output string in 3 ways
Type 1: Print out the entire string directly as a whole.
Type 2: Use the pointer to print out the entire string as a whole.
Type 3: Use the pointer to print out the entire string by a single character.
Type 4: Use the knowledge points of the string.h header file to print out the entire string as a whole.
The first method code is as follows:
#include <stdio.h>
void main(){
char arr[30]="hello world";
printf("%s",arr);
}
The result of the first method code running is as follows:
The code for the second method is as follows:
#include <stdio.h>
void main(){
char arr[30]="hello world";//初始化字符串
char *p;//定义一个指针p
p=arr;//字符串的地址赋给p
printf("%s",p);
}
The result of the second method code operation is as follows:
The third method code is as follows:
#include <stdio.h>
void main(){
char arr[30]="hello world";//初始化字符串
char *p;//定义一个指针p
p=arr;//字符串的地址赋给p
while(*p!='\0'){
printf("%c",*p++);//按单个字符打印输出整个字符串。
}
}
The result of the third method code operation is as follows:
The code for the fourth method is as follows:
#include <stdio.h>
#include <string.h>
void main( ){
char arr[30];//定义一个字符串数组
printf("请输入一个字符串\n");
gets(arr);//从键盘中输入字符串,给字符串数组赋值
printf("打印输出字符串\n");
puts(arr);//整体打印输出字符串数组
}
The result of the code operation of the fourth method is as follows: