c - 我的数组中的偶数位置自动变成 0。你能修复我的代码吗?

标签 c

我编写了这个程序,要求您从元素号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]);
    }
}

结果如下:image 1 , image 2 .

正如你所看到的,甚至连位置都被替换为 0。我不明白为什么以及如何解决这个问题。

最佳答案

以下建议代码

  1. 干净地编译
  2. 更正了 OP 问题评论中列出的所有问题
  3. 执行所需的功能

现在是代码

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

相关文章:

C 和 POSIX Pthreads

c - 没有得到阿姆斯特朗数所需的输出

c - 同一程序在一个编译器而不是另一个编译器中给出编译器错误

c - .c 扩展名与 .C 扩展名

c - 制作一个字符串数组的数组

c - 如何在 "object oriented"C中动态初始化数组?

C - 基本 For 循环

c - 如果我给指针一个普通值会怎样

c - Node v8 变量默认为 NULL,但根据传递的参数重新分配

c++ - 宏中的双哈希 (##) 是什么意思?