指针数组
int main(int argc, const char * argv[]) {
/*
char str1[] = "lnj";
char str2[] = "lmj";
char str3[] = "jjj";
char str4[] = "lk";
char strs[4][20] =
{
"lnj",
"lmj",
"jjj",
"lk"
};
*/
char *str1 = "lnj";
char *str2 = "lmj";
char *str3 = "jjj";
char *str4 = "lk";
// 定义数组的格式: 元素类型 数组名称[元素的个数]
// int a = 10;
// int b = 20;
// int nums[2] = {10 , 20};
char *names[4] =
{
"lnj",
"lmj",
"jjj",
"lk"
};
for (int i = 0; i < 4; i++) {
printf("names[%i] = %s\n", i , names[i]);
}
return 0;
}
指针类型的特点
void change();
void change2();
void change3(int values[]);
void change4(int *p);
char *demo();
char *demo2();
int main(int argc, const char * argv[]) {
/*
只要是数据类型就具备3个特点
1.可以用来定义变量
2.可以用来作为形参的类型
3.作为返回值
*/
/*
int num = 10;
change(num);
printf("num = %i\n", num);
// char *name = "lnj";
// change2(name);
int nums[] = {1, 3, 5};
// change3(nums); // 数组名就是数组的地址
change4(nums); // 数组名就是数组第0个元素的地址
printf("nums[0] = %i\n", nums[0]);
*/
char *name = demo();
printf("name = %s\n", name);
char *name2 = demo2();
printf("name2 = %s\n", name2);
return 0;
}
char *demo2()
{
char name[]= "lnj";
return name;
}
char *demo()
{
char *name = "lnj";
return name;
}
void change4(int *p)
// int *p = nums; == int *p = &nums; == int *p = &nums[0]
// int *p; p = nums; p == nums;
{
p[0] = 998;
}
// 不专业
void change3(int values[])
{
values[0] = 998;
}
/*
void change2(char *p)
{
*p = "lmj";
}
*/
void change(int value)
{
value = 55;
}
实现strlen函数
#include <string.h>
int myStrlen(char *str);
int myStrlen2(char *str);
int myStrlen3(char *str);
int main(int argc, const char * argv[]) {
// 要求自己实现strlen函数
char *name = "lnj";
// size_t size = strlen(name);
int size =myStrlen3(name);
printf("size = %i\n", size);
return 0;
}
int myStrlen3(char *str)
{
int count = 0;
// \0 ascii 0 // 0代表假 1真
while (*str++)count++;
return count;
}
int myStrlen2(char *str)
{
int count = 0;
// *str == str[0]
while (*str++ != '\0') {
count++; // 1
// str = str + 1; // str == str[1]
// str++; // ++可以在变量名前, 也可以在变量名后
}
return count;
}
int myStrlen(char *str)
{
int count = 0;
while (str[count] != '\0') {
count++;
}
return count;
}