指针2
一:指针和字符数组
字符数组和字符串看末尾是否有\0 。“hello ”是字符数组,“hello\0”是字符串
-
代码:
include <stdio.h>
include <string.h>//要用字符串函数就必须带上
int main(){
char C[20];
C[0] = 'J';
C[1] = 'O';
C[2] = 'H';
C[3] = 'N';
C[4] = '\0';
int len = strlen(C);//strlen函数是计算字符串的长度的 ,到'\0'就会停止
printf("%s\n",C);//%s是打印字符串
printf("Length = %d\n",len);
输出结果:
```c
JOHN
Length = 4
- 代码:
#include <stdio.h>
#include <string.h>//要用字符串函数就必须带上
int main(){
char C[] = "JOHN";
printf("Size in bytes = %d\n",sizeof(C));
int len = strlen(C);//strlen函数是计算字符串的长度的 ,到'\0'就会停止
printf("Length = %d\n",len);
}
输出结果:
Size in bytes = 5
Length = 4//strlen函数不会把'\0'算在里面
- 代码:
#include <stdio.h>
void print(char* C){
while(*C != '\0'){
printf("%c",*C);// %c是打印字符
C++;//因为这里的指针C和main里的C是不一样的,这里的C++是形参,可以++
}
printf("\n");
}
int main(){
char C[20] = "Hello";
print(C);
}
输出结果
Hello
- 代码:
#include <stdio.h>
void print(char* C){
int i = 0;
while(C[i] != '\0'){// C[i]可以写成 *(C+i)
printf("%c",C[i]);// %c是打印字符
i++;
}
printf("\n");
}
int main(){
char C[20] = "Hello";
print(C);
}
输出结果:
Hello
代码:
//指针和字符数组
#include <stdio.h>
void print(char* C){
C[0] = 'A';//如果有一个指向数组首地址的指针,可以像使用数组名一样使用
while(*C != '\0'){
printf("%c",*C);
C++;
}
printf("\n");
}
int main(){
char C[20] = "Hello";
// char *C = "Hello";
print(C);
//print("Hello") -->双引号做了3件事:1.申请了空间(在常量区),存放了字符串 2. 在字符串尾加上了'/0' 3.返回的地址,赋值给了指针变量p
}
输出结果:
Aello