【发布时间】:2014-11-17 11:25:04
【问题描述】:
我对 C 语言还是很陌生,并且在我的代码中收到了多个错误消息,如果有人可以向我解释这些错误消息,那就太好了。
我的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
char newINPUT;
char* INPUT = (char*)malloc(1 * sizeof(char));
while((INPUT = getchar()) =! EOF)
char* newINPUT = (char*)realloc(INPUT, 2* sizeof(INPUT));
if(newINPUT =! NULL)
{
INPUT = newINPUT;
}
else
{
free(INPUT);
printf("Out of memory!");
}
return 0;
}
这应该做的是:它应该分配一些内存并读取您键入的内容。当没有分配的内存时,它应该重新分配两倍于以前分配的内存。
错误信息: 警告第 13 行(带有 while 的那一行):赋值使指针从整数不进行强制转换(默认启用) 错误第 13 行:需要左值作为赋值的左操作数 错误第 14 行:“char”之前的预期表达式 第 17 行警告:与第 13 行相同。
如果有人能向我解释一下就好了。谢谢!
编辑:感谢到目前为止的所有答案!他们确实帮助我理解了 malloc 和 realloc。我昨天尝试了另一个自己的版本,但我不确定分配的内存是否正常工作,因为我无法用足够大的输入对其进行测试。这对 realloc 和加倍有效(语法上)吗?
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int main()
{
int *READ; //input
READ = malloc(sizeof(int));
while ((*READ = getchar()) != EOF)
{
if (READ) //if read not null so memory is enough
{
putchar(*READ);
}
else
{
int x;
int* extendedREAD = realloc(READ, (x*2));//expression for "double as much as before"????
if (extendedREAD = NULL) // looking if there s enough memory
{
printf("Error, not enough memory!");
}
x = x * 2;
}
}
return 0;
}
/*
Zeichen einlesen - checken ob eof, wenn nein, dann speicher ausreichend? nein dann vergräßern, sonst zeichen dazuschreiben, dann wieder vonvorne)
*/
谢谢!
【问题讨论】:
-
1)
char newINPUT;:未使用此变量。还有重复的名字。 -
2)
INPUT = getchar():INPUT的类型是char *。getchar()的返回值类型为int。 -
3)
2* sizeof(INPUT):sizeof(INPUT)是sizeof(char*)。它总是相同的值。 -
4)
=!应该是!= -
5)
while((INPUT = getchar()) =! EOF)需要{ }