动态改变C中的结构数组

问题描述 投票:2回答:2

我一直在努力在C中制作动态变化的结构数组。我的数组大小应该根据用户决定写入数据的次数(city1 city2和distance)而改变。我在谈论addEdge函数,它应该在每次用户输入数据时生成更大的数组;它也应该存储在这个数组中的结构。我已经使用了realloc函数,但似乎没有用。在我的主要功能中,我要求用户两次写入他的数据并在每次输入后启动我的功能。由于某种原因,它在第一次函数初始化后工作,但在第二次之后崩溃。我的意图是它在一个循环中工作(用户添加他想要的数据)。这是代码:

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

typedef struct edge{
   char city1[30];
   char city2[30];
   int distance;
}edge;
void addEdge(edge **tab, char* city1, char* city2, int distance, int* n);
int main()
{
    edge *tab;
    tab=(edge*)malloc(0);
    char city1[30], city2[30];
    int distance, n=1;
        printf("\nType cities and distance in form: 'city1 city2 distance'\n");
    scanf("%s %s %d", city1, city2, &distance);
    addEdge(&tab, city1, city2, distance, &n);


        printf("\nType cities and distance in form: 'city1 city2 distance'\n");
    scanf("%s %s %d", city1, city2, &distance);
    addEdge(&tab, city1, city2, distance, &n);


    system("pause");
    return 0;
}


void addEdge(edge **tab, char* city1, char* city2, int distance, int* n)
{

    edge edgeN;
    strcpy(edgeN.city1, city1);
    strcpy(edgeN.city2, city2);
    edgeN.distance=distance;
    *tab=(edge*)realloc(*tab, *n * sizeof(edge));
    *tab[*n-1]=edgeN;
    *n=*n+1;

}
c arrays
2个回答
3
投票

你已陷入运营商优先陷阱。 *tab[*n-1]=edgeN;编译为*(tab[*n - 1]),当你想要的是(*tab)[*n - 1];

如果有疑问,使用parens,它们可能没用,但它将是无害的。

这是导致问题的真正原因,但您也应该遵循Stargateur的建议并测试所有输入和分配函数的返回值。


3
投票

你的一个错误是你永远不会检查你的函数调用可能出现的任何故障。 scanf()返回有效字段数或错误,malloc()realloc()可以返回错误。

edge *tab = NULL;
size_t n = 1; // should be size_t and not int
// ...
if (scanf("%29s %29s %d", city1, city2, &distance) != 3) {
    fprintf(stderr, "wrong input\n");
    exit(EXIT_FAILURE);
}
// ...
edge *tmp = realloc(*tab, *n * sizeof *edge);
if (!tmp) {
  exit(EXIT_FAILURE);
}
*tab = tmp;
© www.soinside.com 2019 - 2024. All rights reserved.