c - 在两个表之间分配数字的问题

标签 c pointers malloc

我想将负数与正数分开在两个单独的数组中。问题是,当我这样做并打印结果时,负数会变成 0。

输出示例:

INPUT
423-5
OUTPUT
423
0

我的 tabData 数组中的数字是正确的,但我的 tabNegatives 数组中的数字不正确。

这是我的代码:

#include <stdlib.h>
#include <stdio.h>

int main (int argc, char **argv) {
    int numberData = 0;
    int numberPositives = 0;
    int numberNegatives = 0;
    int number = 0;
    int *tabData = NULL;
    int *tabPositives = NULL;
    int *tabNegatives = NULL;

    printf("Enter size : ");
    scanf("%d", &numberData);

    tabData = malloc(numberData * sizeof(int));
    for (int i = 0; i < numberData; i++) {
        printf("Enter number: ");
        scanf("%d", &number);
        tabData[i] = number;
        if (number >= 0) {
            numberPositives++;
        } else {
            numberNegatives++;
        }
    }

    //allocation
    tabPositives = malloc(numberPositives * sizeof(int));
    tabNegatives = malloc(numberNegatives * sizeof(int));

    for (int i = 0; i < numberData; i++) {
        if (tabData[i] >= 0) {
            tabPositives[i] = tabData[i];
        } else {
            tabNegatives[i] = tabData[i];
        }
    }

    printf("INPUT\n");
    for (int i = 0; i < numberData; i++) {
        printf("%d", tabData[i]);
    }
    printf("\n");
    printf("OUTPUT\n");
    for (int i = 0; i < numberPositives; i++) {
        printf("%d", tabPositives[i]);
    }
    printf("\n");
    for (int i = 0; i < numberNegatives; i++) {
        printf("%d", tabNegatives[i]);
    }
    printf("\n");

    free(tabData);
    free(tabNegatives);
    free(tabPositives);
}

最佳答案

问题是您的 tabPositivestabNegatives 数组没有 tabData 数组大 - 因此,当您将值分配给[i] 这些数组的元素,您将(在某些时候)超出范围。

您应该为这两个数组中的每一个保留单独的索引,如下所示:

    int iPos = 0, iNeg = 0; // Current indexes for each pos/neg array
    for (int i = 0; i < numberData; i++){
        if (tabData[i] >= 0){
            tabPositives[iPos++] = tabData[i]; // Use current "pos" index then increment
        }else {
            tabNegatives[iNeg++] = tabData[i]; // Use current "neg" index then increment
        }
    }

关于c - 在两个表之间分配数字的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59530628/

相关文章:

c - 你如何从 C 文件中读入一个数字和一个字符串?请记住,文件中的某些行只有数字而不是字符串

c - 使用 realloc() 初始化内存

c - 不同成员的结构排序

c++ - 为什么 std::cout 将 volatile 指针转换为 bool?

将元素从列表更改为末尾

c - C 中的全局变量和动态分配变量有什么区别?

C 头文件问题 : #include and "undefined reference"

c - C 中的 qsort(动态分配)

c - c中的分配存储和二进制fwrite短裤

c - 数组类型和使用 malloc 分配的数组之间的区别