我必須編寫一個程序來存儲和打印出內存中的整數。我必須使用realloc。基本上,該程序分配2個整數的大小。當輸入給出2個整數時,它應該重新分配1個int空間並打印出double。接下來,當輸入端爲3個整數,它應該分配爲INT 2個空格,並打印出雙..等..C編程:如何在此程序中使用realloc?
Test cases:
input file in.0:
------
4
------
expected output:
------
4
------
=================================================
input file in.1:
------
4 5
------
expected output:
------
4
5
double
------
==================================================
input file in.2:
------
4 5 3
------
expected output:
------
4
5
double
3
double
------
===================================================
input file in.3:
------
4 5 3 2 9
------
expected output:
------
4
5
double
3
double
2
9
double
我寫了這個程序,但它不能正確分配內存。有人能指導我寫作方向嗎?
int main(void)
{
int c;
int digit;
int count = 0;
int d_size = 1;
int init_size = 2;
int *p = (int *) malloc(sizeof(int) * init_size);
while((c = scanf("%i", &digit)) != EOF)
{
if (c == 1)
{
*(p+count) = digit;
count++;
}
else
{
printf("not valid");
}
printf("%i\n", digit);
if (count >= 2)
{
printf("double\n");
p = (int *) realloc(p, sizeof(int) * d_size);
d_size = d_size * 2;
}
}
不要投該死該死的的realloc的該死的返回值! – 2012-06-27 18:53:23
「不能正確分配內存」 - 請更具體。它以什麼方式不起作用? –
@ H2CO3:+1我有一個罐裝評論,因爲我經常在這裏看到它* soooooo *。這不是C++,不要施加'malloc'的返回值(在這種情況下是'realloc')! –