通过超出数组的限制重新分配数组的大小
Reallocating the size of the array by exceeding the limit of it
我无法解决问题。该程序必须根据用户的需要增加数组的大小。但是,它会跳过条件并开始显示数组本身。
int main() {
int *ptr;
int limit;
int sum = 0;
int ans;
printf("enter the limit of the array\n");
scanf_s("%d", &limit);
ptr = (int *)malloc(limit * sizeof(int));
for (int i = 0; i < limit; i++) {
printf("enter element %d : ", i + 1);
scanf_s("%d", (ptr + i));
if (i = limit) {
printf("do you want to stop entering?\n");
printf("\t\t1\t0\n");
if (scanf_s("%d", &ans) == '1') {
break;
} else
if (scanf_s("%d", &ans) == '0') {
limit += 5;
ptr = (int *)realloc(ptr, limit * sizeof(int));
printf("memory re-allocation is completed succesfully!\n");
}
}
}
for (int i = 0; i < limit; i++) {
printf("\nthis is your %d. element : %d\n", i + 1, *(ptr + i));
}
return EXIT_SUCCESS;
}
代码中的 if
语句:
if (i = limit)
不比较 i
和 limit
。相反,它将 limit
的值分配给 i
,然后检查此表达式的结果是否为非零。如果是,则进入该块,否则将跳过。
=
是赋值运算符。使用相等运算符 ==
比较两个操作数。
if (i == limit)
我无法解决问题。该程序必须根据用户的需要增加数组的大小。但是,它会跳过条件并开始显示数组本身。
int main() {
int *ptr;
int limit;
int sum = 0;
int ans;
printf("enter the limit of the array\n");
scanf_s("%d", &limit);
ptr = (int *)malloc(limit * sizeof(int));
for (int i = 0; i < limit; i++) {
printf("enter element %d : ", i + 1);
scanf_s("%d", (ptr + i));
if (i = limit) {
printf("do you want to stop entering?\n");
printf("\t\t1\t0\n");
if (scanf_s("%d", &ans) == '1') {
break;
} else
if (scanf_s("%d", &ans) == '0') {
limit += 5;
ptr = (int *)realloc(ptr, limit * sizeof(int));
printf("memory re-allocation is completed succesfully!\n");
}
}
}
for (int i = 0; i < limit; i++) {
printf("\nthis is your %d. element : %d\n", i + 1, *(ptr + i));
}
return EXIT_SUCCESS;
}
代码中的 if
语句:
if (i = limit)
不比较 i
和 limit
。相反,它将 limit
的值分配给 i
,然后检查此表达式的结果是否为非零。如果是,则进入该块,否则将跳过。
=
是赋值运算符。使用相等运算符 ==
比较两个操作数。
if (i == limit)