C语言,在书上抄的运行错误!

来源:百度知道 编辑:UC知道 时间:2024/05/21 15:55:04
目的:使用malloc()函数为字符串数据分配内存空间.

#include<stdio.h>
#include<stdlib.h>

char count,*ptr,*P;

int main(void)
{

ptr=malloc(35*sizeof(char));

if(ptr==NULL)
{
puts("menory allocation error.");
return 1;
}

p=ptr;
for(count=65;count<91;count++)
*p++=count;
*p='\0';
puts(ptr);
free(ptr);
return 0;
}
哪里错了呢?

有两错,我给在你的原程序上注释出来了,但没有改正,你自己动手体验一下Debug的乐趣吧:
#include<stdio.h>
#include<stdlib.h>

char count,*ptr,*P; //大小写错了,这个*P要改成小写的:*p

int main(void)
{

ptr=malloc(35*sizeof(char)); //这里要做个类型转换,
//就是把这句改成:ptr=(char*) malloc(35*sizeofchar));

if(ptr==NULL)
{
puts("menory allocation error.");
return 1;
}

p=ptr;
for(count=65;count<91;count++)
*p++=count;
*p='\0';
puts(ptr);
free(ptr);
return 0;
}