字符串与数组
#define _CRT_SECURE_NO_WARNINGS #include<stdlib.h> #include<string.h> #include<stdio.h> void main() { char a[] = "i am a student"; //默认\0 结尾,为字符串(字符数组表示) char b[64]; printf("strlen(a)=%d,sizeof(a)=%d\n", strlen(a), sizeof(a)); //str为字符串长度14 sizeof为数组长度15,包括\0 int i = 0; for (i = 0; *(a + i) != '\0'; i++) // a[i] = *(a+i) a代表数组首地址,i步长为1 { *(b + i) = *(a + i); } *(b + i) = '\0'; //若不将最后一位设置为\0,则表示单纯的字符数组,不是字符串,不能用%s输出 printf("a:%s\n", a); printf("b:%s\n", b); system("pause"); return ; }
void copystr(char * from,char * to) //拷贝字符串函数 { int i; //1. //for (i = 0; *(from + i) != '\0'; i++) //{ // //to[i] = from[i]; //to[i] 和 *(to+i)一样 // *(to + i) = *(from + i); //} //*(to + i) = '\0'; //2. //for (; *from != '\0';) //{ // *to++ = *from++; //*to=*from to++;from++ //} //*to = '\0'; //3 //while ((*to = *from) != '\0') //{ // to++; // from++; //} while ((*to++ = *from++) != '\0') { } return; } void main() { char from[] = "i am a student"; //提前给from 和 to 分配内存 char to[64]; copystr(from, to); printf("%s\n",to); system("pause"); return; }