C语言字符数组与字符串简介

来源:互联网 发布:mac隐藏的照片 编辑:程序博客网 时间:2024/05/01 01:46
#include<stdio.h>#include<stdlib.h>void main(){//数组的定义char str[5] = { 'a', 'b', 'c', 'd', 'e' };for (int i = 0; i < 5; i++){//数组名可以当成指针,但是数组名是常量printf("%c,%c\n", str[i],*(str+i));}//对于字符数组可以用数组的方式输出 但要是用字符串的形式就会变得不一样//这是因为用字符串输出时直到遇见'\0'时才会停止输出,而对于str,定义数组时是满数组定义的//缺少‘\0’,在输出abcde后会出现乱码printf("%s\n\n\n", str);    system(str);  //不能执行 以字符串的形式运行 但没有'\0',不知道截取多少位 直到遇见'\0'为止//下面两种赋值都会出现错误,会出现错误 这是因为str3是常量  不能对其进行赋值//char str3[10];//str3 = "ipconfig";       //str3 = { 'A' };//下面是定义一个5个元素的字符数组,但实际初始化了4个元素,最后一个元素会默认为'0'char str1[5] = { 'c', 'a', 'l', 'c' };printf("%s", str1);system(str1);  //可以直接用数组名运行,但是以字符串的形式  成功打开calc//下面是用字符串对字符数组初始化  但不能满数组初始 因为没有'\0'的位置,//字符串后面系统会默认跟一个'\0'//char *str2[10] = "mapaintaaa";char str2[10] =  "mspaint" ;printf("\n\n%s\n", str2);system(str2);//下面是用指针来指向字符串的首地址//char *pc = "ipconfig";  这种方式也是可以的char *pc;pc = "ipconfig";         //这种方式是可以的 但字符数组这样初始不行printf("%s\n", pc);system(pc);//下面是定义二维字符数组char twostr[5][11] = { "color 5f","title my","echo style","tasklist","write" };for (int i = 0; i < 5; i++){printf("\ntwostr[%d]=%s", i, twostr[i]);   //在这里要注意 twostr[i] 是可以打印的}for (int i = 0; i < 5; i++){system(twostr[i]);}getchar();}

0 0
原创粉丝点击