#include <stdio.h>
#define MSG "You must have many talents.Tell me some."//一个符号字符串常量
#define LIM 5
#define LINELEN 81 //最大字符串长度+1
int main()
{
char name[LINELEN];
char talents[LINELEN];
int i;
//初始化一个大小已确定的char数组
const char m1[40] = "Limit yourself to one line`s worth.";
//让编译器计算数组大小
const char m2[] = "If you can`t think of anything,fake it.";
//初始化一个指向字符串的指针
const char *m3 = "\nEnough about me - what`s your name?";
//初始化一个字符串指针的数组
const char *mytal[LIM] = {
"Adding numbers swiftly",
"Multiplying accurately",
"Stashing data",
"Following instructions to the letter",
"Understanding the C language"
};
for(i=0;i<LIM;i++)
puts(mytal[i]);
puts(m3);
gets(name);
printf("Well,%s,%s\n",name,MSG);
printf("%s\n%s\n",m1,m2);
gets(talents);
printf("%s\n",name);
return 0;
}
数组与指针
指针方式 char *head = "weqwqeqeqewqeweq";
head 变量
数组方式 char heart[] ="weqwqeqeqewqeweq";
heart 为常量
都可以使用数组符号
head[1]
heart[1]
都可以使用指针加法
*(head+1)
*(heart+1)
head++
//赋值(赋值语句左边必须是变量)
head = heart //指针指向数组 合法
heart = head//非法(heart不是变量是常量)
建议初始化一个指向字符串的指针时使用const修饰符,防止非法操作
const char *p1 ="dssada";
二维数组和指针数组的区别
//指针数组(保存的其实是指针地址,字符串本身不存在数组内)
const char *mytal[LIM] = { "Adding numbers swiftly",
"Multiplying accurately", "Stashing data",
"Following instructions to the letter", "Understanding the C language" };
//二维数组(字符串本身存在数组内)
char mytal_2[LIM][LINLIM]
区别
mytal 指针数组建立的是一个不规则(ragged)的数组,每一行长度由初始化的字符串决定(不浪费空间)
mytal_2 二维数组建立了一个所有行的长度都相同的矩形(rectangular)
#include <stdio.h>
int main(void)
{
char str1[] = "qazwsxedc";
char str2[] = "123456789";
char *a1 = str1;
char *a2 = str2;
*a1++ = *a2++;//先赋值后++两边都是
++*a1 = ++*a2;//先++再赋值两边都是
puts(str1);
return 0;
}