【c&c++】C语言 char*和char[]用法

发布时间 2023-04-06 09:42:27作者: opensmarty

char []定义的是一个字符数组,注意强调是数组。
char * 定义的是一个字符串指针,注意强调是指针。
char *s定义了一个char型的指针,它只知道所指向的内存单元,并不知道这个内存单元有多大,所以:

当char *s = “hello”;后,不能使用s[0]=‘a’;语句进行赋值。这是将提示内存不能为"written"。

当用char s[]=“hello”;后,完全可以使用s[0]=‘a’;进行赋值,这是常规的数组操作。
若定义:

char s[] = "hello";
char *p = s;

也可以使用p[0] = ‘a’;因为这是p ==s,都是指向数组的指针。

char *s = (char *)malloc(n);//其中n为要开辟空间的大小

相当于

char s[n];
#include <stdio.h>
int main(int argc, char* argv[]) {
    char* buf1 = "abcd1234";
    char buf2[] = "abcd1234";
    printf("size of buf1: %d\n", sizeof(buf1));
    printf("size of buf2: %d\n", sizeof(buf2));
    printf("长度为:%d  %d\n", strlen(buf1), strlen(buf2));
return 0;

size of buf1: 4
size of buf2: 9
长度为:8 8