怎么样使用指针和malloc函数,输入未知长度的字符串到数组

C语言 码拜 8年前 (2016-05-16) 2237次浏览
本人想输入任意长度的字符串到数组中,由于数组元素个数未知,必须要用malloc函数动态分配内存,并用指针引用之。但为什么程序运行就崩溃了呢?请各位高手指点一下。谢谢!
代码如下:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
char str[]={0};//用于存放字符串
char *pva=(char *)malloc(sizeof(str));
pva=str; //指针指向数组
const int LENGTH=50;
printf(“\nPlease enter a string up to %d characters:”,LENGTH);
scanf(“%s”,pva);
printf(“%s”,*pva);
return 0;
}
解决方案

80

你这个逻辑完全不对。
1.char *pva=(char *)malloc(sizeof(str));这句话只申请了一个字节的空间,你打印下sizeof(str)就知道了
2.printf(“%s”,*pva);不需要加*
3.你让pva指向str?你输入的字符串是写在pva所malloc出来的空间里的,而不是str里的

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(void)
{
	const int LENGTH = 50;
	char str[] = { 0 };//用于存放字符串
	printf("sizeof(str):%d\n", sizeof(str));
	char *pva = (char *)malloc(LENGTH + 1);
	//pva = str; //指针指向数组

	printf("\nPlease enter a string up to %d characters:", LENGTH);
	scanf("%s", pva);
	printf("%s\n", pva);
	return 0;
}

CodeBye 版权所有丨如未注明 , 均为原创丨本网站采用BY-NC-SA协议进行授权 , 转载请注明怎么样使用指针和malloc函数,输入未知长度的字符串到数组
喜欢 (0)
[1034331897@qq.com]
分享 (0)