[英]Dynamic memory allocation with int array
我有一个作业,必须接受用户的输入。 我不能使用链表,只能使用数组,所以我的计划是:
分配一些内存。
如果需要重新分配,这意味着我已达到分配的单元数:
尝试重新分配。 如果成功,那就太好了。
如果我们无法重新分配,则打印输入,释放内存并重新分配。
我真的不能决定告诉我如何到达分配的内存末尾的命令,这就是为什么我需要您的帮助。 我写:
if (i==(MAX_CHARS_INPUT-1))
但是我不确定。
编码:
#include <stdio.h>
#include <stdlib.h>
#define MAX_CHARS_INPUT 200
#define D_SIZE 2
void printWithMalloc(){
int charSize=1;
int *ptr=malloc(MAX_CHARS_INPUT*sizeof(charSize));
int i=0, j=0, c;
printf("please enter a string\n");
while ((c=getchar())!=EOF && c!='\n')
{
ptr[i++]=c;
if (i==(MAX_CHARS_INPUT-1)) /*if we need to realloc*/
{
int *temp=realloc(ptr,D_SIZE*MAX_CHARS_INPUT*sizeof(charSize));
if (temp==NULL) /*realloc failed*/
{
printf("you wrote:\n");
while(j<=i)
putchar(ptr[j++]);
free(ptr);
ptr=(int*)malloc(MAX_CHARS_INPUT*sizeof(charSize));
}
else
ptr=temp;
}
}
}
int main(){
printWithMalloc();
return 0;
}
谢谢!
问题的确与您的状况有关:
if (i==(MAX_CHARS_INPUT-1))
此方法有效,但仅在您首次达到此限制时有效。 当您重新realloc
缓冲区时,缓冲区会变大,但是您不会检查是否耗尽了该空间。 假设我输入了500个字符。 当读取第199个字符时,缓冲区重新分配为400个字符大。 但是, i
仅在第199个字符处进行检查,因此当到达第400个字符时,它将用尽缓冲区。
第二个问题是,当您重新分配缓冲区时,它将仅增长到400个字符( D_SIZE * MAX_CHARS_INPUT
),并且不会更大。
第三个问题是当您重新malloc
(即,重新realloc
失败时),您不会重置i
因此它将立即写入缓冲区的末尾。
如现在删除的答案中所建议。 跟踪缓冲区大小:
size_t buffSize = MAX_CHARS_INPUT;
当您重新分配,更新buffSize
第一,然后用其作为参数传递给realloc
:
buffSize *= D_SIZE; // double the buffer-size
temp = realloc(ptr, buffSize * sizeof(*temp)); // using sizeof *temp is less confusing and less error-prone
当然:还可以更新您的状况:
if(i == buffSize - 1)
而当你重新malloc
复位i
和buffSize
:
buffSize = MAX_CHARS_INPUT;
ptr = malloc(buffSize*sizeof(*ptr));
i = 0;
虽然重malloc
ING不是很明智,如果分配失败,因为通常有更大的问题(除非内存受到很大限制)。 并且(尤其是因为您不检查该malloc
的结果)可能会出现问题,因为该malloc
也可能会失败。 分配失败后退出程序并不罕见。
您的代码中几乎没有出错的地方,新代码是:
#include <stdio.h>
#include <stdlib.h>
#define MAX_CHARS_INPUT 200
#define D_SIZE 2
void printWithMalloc(){
//int charSize=1; you don't need this.
//int *ptr=malloc(MAX_CHARS_INPUT*sizeof(charSize));
char *ptr=malloc(MAX_CHARS_INPUT*sizeof(char));//sizeof(char) will give you the block size, MAX_CHARS_INPUT: gives you the number of blocks to be allocated and pointer type is char, since you want to save char(s), right?
int i=0, j=0, c;
printf("please enter a string\n");
//while ((c=getchar())!=EOF && c!='\n')
while ((c=getchar())!='\r') //'\r' is for enter key... since the user input is coming from console not form a file, right?
{
ptr[i++]=c;
if (i==(MAX_CHARS_INPUT-1)) /*if we need to realloc*/
if (i==MAX_CHARS_INPUT) // i is already incremented in i++
{
//int *temp=realloc(ptr,D_SIZE*MAX_CHARS_INPUT*sizeof(charSize));
char *temp=realloc(ptr,D_SIZE*MAX_CHARS_INPUT*sizeof(char));
if (temp==NULL) /*realloc failed*/
{
printf("you wrote:\n");
while(j<=i)
putchar(ptr[j++]);
free(ptr);
ptr=(char*)malloc(MAX_CHARS_INPUT*sizeof(char));
}
else
ptr=temp;
}
}
}
int main(){
printWithMalloc();
return 0;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.