我编写了这个程序,要求您从元素号1开始输入一维数组中元素的值,当您输入值0时它将停止。
void main() {
int *A;
int n, j, B;
int i = 1;
A = malloc(i * sizeof(int));
printf("Enter the element A[%d] = ", i);
scanf("%d",&A[i]);
while (i>=1) {
if (A[i] != 0) {
i = i + 1;
A = realloc(A, i * sizeof(int));
printf("Enter the element A[%d] = ",i);
scanf("%d",&A[i]);
} else {
break;
}
}
for (j = 1 ; j <= i; j++) {
printf("\t%d", A[j]);
}
for (j = 1; j <= i; j++) {
free(A[j]);
}
}
正如你所看到的,甚至连位置都被替换为 0。我不明白为什么以及如何解决这个问题。
最佳答案
以下建议代码
- 干净地编译
- 更正了 OP 问题评论中列出的所有问题
- 执行所需的功能
现在是代码
#include <stdio.h> // scanf(), printf(), perror()
#include <stdlib.h> // realloc(), exit(), EXIT_FAILURE
int main( void )
{
int *A = NULL;
int temp;
size_t i = 0;
printf("Enter the element A[%lu] = ", i+1);
while( 1 == scanf("%d",&temp) )
{
int* tempRealloc = realloc(A, (i+1) * sizeof(int));
if( !tempRealloc )
{
perror( "realloc failed" );
free( A ); // cleanup
exit( EXIT_FAILURE );
}
// implied else, realloc successful
A = tempRealloc;
A[i] = temp;
i++;
if( !temp ) // 0 entered by user
break;
printf("Enter the element A[%lu] = ",i+1);
}
for (size_t j = 0 ; j < i; j++)
{
printf("\t%d", A[j]);
}
free( A );
} // end function: main
关于c - 我的数组中的偶数位置自动变成 0。你能修复我的代码吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43900347/