strcpy()崩溃

C语言 码拜 7年前 (2017-05-05) 1443次浏览
下面的代码实在搞不懂为什么会崩溃,应该是strcpy的问题

#include <stdio.h> 
#include <string.h>
typedef struct T
{
	char *name;
	int num;
}test;
int main()
{
	test *p = (test*)malloc(sizeof(test));
	strcpy(p->name,"jim");
	printf("%s\n",p->name);
	return 0; 
}
解决方案

10

给结构分配了内存,但没给name分配空间。

10

name没有malloc空间。

20

你的结构体里只放了一个char指针和一个int变量,所以字符串没地方放,应该这样

    test *p = (test*)malloc(sizeof(test));
    p->name = (char*)malloc(64*sizeof(char));//64是你放的最多的字符数
    strcpy(p->name,"jim");

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明strcpy()崩溃
喜欢 (0)
[1034331897@qq.com]
分享 (0)