C语言中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(www.jb51.net));//其中n为要开辟空间的大小

这句话其实相当于:

char s[n];

定义的也是一个指向数组的指针,便可进行数组的下标操作

例子

#include <stdio.h>

int main(int argc, char* argv[]) {
char* buf1 = "this is a test";
char buf2[] = "this is a test";
printf("size of buf1: %d\n", sizeof(buf1));
printf("size of buf2: %d\n", sizeof(buf2));
return 0;
}

结果是:

$ > ./main
size of buf1: 4

size of buf2: 15


------------------------------------------------------------------------------------------------------------------------------------------------------------------

在编写这道题目时,用了VS2010:

使用C/C++编写函数,实现字符串反转,要求不使用任何系统函数,且时间复杂度最小。

当运行下列代码时,报出了错误:0xC0000005: Access violation writing location 0x00125744。

char* reverseString(char* s) {
    if(s == NULL){
		return "";
	}
	int length = 0;
	
	for(length;;length++){
		if(s[length] == '\0'){
			break;
		}
	}
	for(int i = 0;i<length/2;i++){
		char temp;
		temp = s[i];
		s[i] = s[length-1-i];
		s[length-1-i] =temp;
	}
	return s;
}
上网查了查,发现了上面关于char*和char[]的区别。但是这段代码在leetcode上却通过了。

后来把函数改写成了:

char* reverseString(char* s) {
    if(s == NULL){
		return "";
	}
	int length = 0;
<span style="white-space:pre">	</span>for(length;;length++){
		if(s[length] == '\0'){
			break;
		}
	}
<span style="white-space:pre">	</span>char *newString = (char*)malloc(length*sizeof(char));
	for(int i = 0;i<length;i++){
		newString[i] = s[length-1-i];
	}
	newString[length] = '\0';
	return newString;
}

但似乎用了系统函数malloc。

而直接定义一个char数组,char newString[length]又会报错:expected constant expression。这是因为:

The sizes of array variables in C must be known at compile time. If you know it only at run time you will have to malloc some memory yourself instead.

好纠结啊,大家有什么方法吗?


When you write char myArray[6]="Hello"; you are allocating 6 chars on the stack (including a null-terminator).

Yes you can change individual elements; e.g. myArray[4] = '\0' will transform your string to "Hell" (as far as the C library string functions are concerned), but you can't redefine the array itself as that would ruin the stack.

Note that [const] char* myArray = "Hello"; is an entirely different beast: that is read-only memory and any changes to that string is undefined behaviour.


Array is a non modifiable lvalue. So you cannot modify it.If you wish to modify the contents of the array, use strcpy.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值