首页 > 学院 > 开发设计 > 正文

c语言字符串与数组还有指针的总结(1)

2019-11-06 07:54:09
字体:
来源:转载
供稿:网友
#include <stdio.h>#include <string.h>int main(){ /* char *str = {'h','e','l','l','o'};//运行错误,scalar object 'str1' requires one element in initializer */ /* char *str = "hello";//hello在静态存储区,内容是不可更改的,str这个指针在栈区 str[0] = 'H';//静态存储区不可被修改 */ /* char *str = "hello"; strcpy(str,"hello world");//运行错误,strcpy要复制到内存里,这里没有分配内存 */ char *str = "hello"; str="world";//从指向hello转为指向world PRintf("%c/n",str[0]); printf("a way of visiting string in pointer:%c/n",*(str+2)); printf("offset visiting:%s/n",str+2); printf("length:%d,content:%s/n",strlen(str),str); return 0;}#include <stdio.h>#include <string.h>int main(){ /* char str[] = {'h','e','l','l','o'};//运行有点问题,数组转换成字符串后可能没有'/0'的结尾 */ /* char str[] = "hello"; printf("%d/n",sizeof(str)); strcpy(str,"worldfdsa"); printf("%d/n",sizeof(str));//用strcpy复制后的str的长度并不增加,所以只要重新赋值长度大于以前的,会出现问题的,不推荐 */ /* char str[] = "hello"; str="world";//运行错误,这里相当于一个数组,数组的头指针指向不变 */ char str[] = "world"; str[0] = 'W'; printf("%c/n",str[0]); printf("a way of visiting string in pointer:%c/n",*(str+2)); printf("offset visiting:%s/n",str+2); printf("length:%d,content:%s/n",strlen(str),str); return 0;}#include <stdio.h>#include <string.h>#include <stdlib.h>int main(){ /* char *str = (char *)malloc(sizeof(char)*20);//在堆区 str = {'h','e','l','l','o'};//运行错误 */ char *str = (char *)malloc(sizeof(char)*20); strcpy(str, "world"); str[0] = 'W'; /* char *str = (char *)malloc(sizeof(char)*20); str = "world";//这样你动态分配的就没了,成了一块野区,造成了内存泄漏 str[0] = 'W';//由于指向了静态存储区,所以不可被修改 */ printf("%c/n",str[0]); printf("a way of visiting string in pointer:%c/n",*(str+2)); printf("offset visiting:%s/n",str+2); printf("length:%d,content:%s/n",strlen(str),str); free(str); return 0;}#include <stdio.h>#include <string.h>int main(){ /* char str[20]={'h','e','l','l','o'}; str[0] = 'H'; */ /* char str[20];//在栈区 printf("%d/n",sizeof(str)); strcpy(str, "world"); printf("%d/n",sizeof(str));//赋值内容不可超过上限 */ /* char str[20] = "hello"; str = "world";//运行错误,数组的头指针不可指向静态存储区 */ char str[20] = "world"; str[0] = 'W'; printf("%c/n",str[0]); printf("a way of visiting string in pointer:%c/n",*(str+2)); printf("offset visiting:%s/n",str+2); printf("length:%d,content:%s/n",strlen(str),str); return 0;}

char *str = "hello"; 这里的指针str是在栈区,而”hello/0”是在静态存储区,一旦赋值就不允许修改,但是可以访问,str指向了字符串内容的头指针

char str[] = "hello"; 这里的指针str是在栈区,”hello/0”也是在栈区,它相当于一个数组,你不可以改变它重新指向一个静态存储区的字符串,可以修改

char *str = (char *)malloc(sizeof(char)*20); str在栈区,数组内容在堆区,用strcpy赋值或者一个个元素赋值,可以被修改,若使用 str = "world"; 会导致str的指针指向了静态存储区的”world/0”字符串,导致内存泄漏

char str[20] = "hello"; str在栈区,数组内容在栈区,初始化时赋值或者一个一个元素赋值或者用strcpy赋值,你不可以改变它重新指向一个静态存储区的字符串,可以被修改

以上只要赋值方式正确,均可通过数组方式或者指针方式访问其中内容


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表