[英]trouble printing after allocating memory
使用malloc
,将显示name
,但在分配内存并键入一个string
, puts
根本不会打印该字符串, printf
也不...为什么?
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
char *name;
int size;
printf("enter the size if name below\n");
scanf("%d", &size);
name =(char*) malloc(size * sizeof(char));//since my compiler returns pointr of type void, you have specify whether (int*) or (char*)
if (name== NULL)
printf("memory allocation failed,,,\n");
printf("%s\n",name);
printf("enter name below\n");
scanf("%s", name);
printf("name is\n%s", name);
name = (char*)realloc(name, 100*sizeof(char));
if (name == NULL)
printf("failed\n");
gets(name);
getchar();
puts(name);
free(name);
return 0;
}
首先, malloc/realloc
不返回void
,它们返回void*
,它完全能够隐式转换为任何其他指针类型。 在C中显式执行此操作不是一个好主意,因为它可以隐藏某些细微的错误。
另外, sizeof(char)
始终为 1,您不需要乘以它。
第三,使用gets
是一个非常糟糕的主意,因为没有办法防止缓冲区溢出。 有很多更好的方法可以进行用户输入。
至于特定的问题,我怀疑它很可能仍在getchar
周围。 gets
将从用户那里获得一行(包括换行符),但是,除非您输入另一个字符(如果使用基于行的I / O,可能是整行),否则它将似乎挂起。 输入名称后,只需再次按ENTER即可进行检查。
在gets()
处尝试fgets()
或scanf()
gets()
,它将起作用
您发布的程序导致undefined behavior
。 这是因为
printf("%s\n",name);
变量name
没有任何内容,您正在尝试在分配的内存中打印该值。 首先,在打印之前,您需要为name
分配一些值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.