简体   繁体   English

在C中使用指针和malloc时出现多个错误消息

[英]Multiple error messages while working with pointer and malloc in c

I'm still very new to C and get multiple error messages in my code and it would be nice if someone could explain these error messages to me. 我对C还是很陌生,并且在我的代码中收到了多个错误消息,如果有人可以向我解释这些错误消息,那就太好了。

My code: 我的代码:

#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;

}

What this shall do is: It should allocate some memory and read what you type. 这应该做的是:它应该分配一些内存并读取您键入的内容。 When there is no allocated memory left it should reallocate double as much memory as has been alocated before. 如果没有分配的内存,则应重新分配两倍于以前分配的内存。

Error messages: warning line 13(that line with while): assignement makes pointer from integer without cast (enabled as default) error line13: lvalue required as left operand of assignement error line14: expected expression before 'char' warning line 17: same as line 13. 错误消息:警告行13(带有while的行):赋值使指针从整数开始而不进行强制转换(默认启用)错误行13:要求左值作为赋值的左操作数错误行14:'char'警告行​​之前的期望表达式17:与第13行。

Would be nice if someone could explain that to me. 如果有人可以向我解释这一点会很好。 Thanks! 谢谢!


EDIT: Thanks for all the answers so far! 编辑:感谢到目前为止的所有答案! They truly helped me in understanding malloc und realloc. 他们确实帮助我了解了malloc和realloc。 I've tried another own version yesterday, but I'm not sure if the allocated memory works right since I can't test it with an input large enough. 我昨天尝试了另一个自己的版本,但是由于不能用足够大的输入来测试它,所以我不确定分配的内存是否正常工作。 Would that work (syntaxwise) with the realloc and the doubling? 在重新分配和加倍的条件下(在语法上)可行吗?

    #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)
*/

Thank you! 谢谢!

Lots of issues here... 这里有很多问题...

int main()
{
  char newINPUT;

  char* INPUT = (char*)malloc(1 * sizeof(char));

Don't cast the result of a call to malloc() ; 不要将调用的结果malloc()malloc() it's unnecessary and can cause unexpected problems. 这是不必要的,并且可能导致意外的问题。

  while((INPUT = getchar()) =! EOF)

Two problems here. 这里有两个问题。 First, a =! b 首先, a =! b a =! b means "set a to the logical complement of b " . a =! b表示“将a设置为b的逻辑补” You probably wanted to use something of the form a != b ( " a not equal to b " ). 您可能想使用a != b形式a != b东西( a不等于b )。 Second, getchar() returns an int value. 其次, getchar()返回一个int值。 If you try to store the return value in a char container, you may find that it will never be equal to EOF . 如果尝试将返回值存储在char容器中,则可能会发现它永远不会等于EOF

    char* newINPUT = (char*)realloc(INPUT, 2* sizeof(INPUT));

Here you are redeclaring newINPUT as a char* pointer. 在这里,您将newINPUT重新声明为char*指针。 You declared it as char newINPUT earlier on. 您之前char newINPUT其声明为char newINPUT This will cause a compilation error. 这将导致编译错误。

    if(newINPUT =! NULL)

You are setting newINPUT to the logical complement of NULL here. 您在此处将newINPUT设置为NULL的逻辑补码。 I think you meant if (newINPUT != NULL) . 我想你是说if (newINPUT != NULL) You could have simply used if (newINPUT) instead. 您可以简单地使用if (newINPUT)代替。

(Nonsense about memory leak deleted — my mistake!) (关于内存泄漏的胡言乱语已删除-我的错!)

Overall, your program logic is flawed because you are attempting to double the allocated memory for every single character of input. 总体而言,您的程序逻辑存在缺陷,因为您试图为输入的每个单个字符将分配的内存加倍。 So even if you fixed the above problems, you would run out of memory after inputting about 32 characters. 因此,即使您解决了上述问题,在输入大约32个字符后,内存也将耗尽。


Suggested rewrite: 建议改写:

The following code stores the current size of the input buffer in size , and the length of the input string in nchars . 下面的代码存储在输入缓冲器的当前大小size ,并且在所述输入字符串的长度nchars Both are initialised to zero. 两者都初始化为零。 The buffer location itself ( char *input ) can be initialised to NULL , because a call to realloc() with a null pointer is equivalent to calling malloc() . 缓冲区位置本身( char *input )可以初始化为NULL ,因为使用空指针调用realloc()等同于调用malloc() That means we can eliminate one system call from the code. 这意味着我们可以从代码中消除一个系统调用。

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

int main() {
  char *input=NULL, *new_input;
  int c, size=0, nchars=0;

  while (1) {
    if (size==nchars) {
      size = size*2 + (size==0);  /* (size==0) is 1 if size==0, zero othewise */
      if (!(new_input = realloc(input,size))) {
        puts("Out of memory");
        free(input);
        return 1;
      }
      input = new_input;
      printf("Buffer reallocated; new size is %d byte(s)\n",size);
    }
    if ((c=getchar())==EOF) {
      input[nchars] = '\0';  /* Terminate the input string */
      break;
    }
    input[nchars++] = c;
  }

  printf("Buffer size:   %d\n"
         "String length: %d\n"
         "Input was:     %s\n",size,nchars,input);
  free(input);
  return 0;
}

An example of a modification 修改示例

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

int main(void){
    int ch;
    char* INPUT = (char*)malloc(1 * sizeof(char));
    int input_buf_size = 1;
    int input_count = 0;

    while((ch = getchar()) != EOF){
        INPUT[input_count] = ch;
        input_count += 1;
        if(input_count == input_buf_size){
            char *newINPUT = (char*)realloc(INPUT, input_buf_size *= 2);
            if(newINPUT != NULL){
                INPUT = newINPUT;
            } else {
                free(INPUT);
                printf("Out of memory!");
                exit(EXIT_FAILURE);
            }
        }
    }
    INPUT[input_count] = '\0';
    puts(INPUT);
    free(INPUT);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM