【问题标题】:Problem of init array of structs with list data带有列表数据的结构初始化数组的问题
【发布时间】:2020-08-08 12:35:13
【问题描述】:

我发现自己故障排除了很长时间,并试图找出我的功能出了什么问题。 我必须说我不是 100% 确定这是否是正确的语法来做我想做的事。 我有这个函数,假设用列表数据初始化一维结构数组。 该功能之前的所有内容都可以正常工作并经过测试。 这是有问题的函数:

Three* createThreeArr(Three** arr, ListThree** head, int counter)
{
    int i = 0;
    ListThree* pIndex = *head;
    *arr = (Three*) calloc(counter,sizeof(Three));
    for (i = 0; i < counter ; i++)
    {
        (arr[i])->col   = pIndex->data.col;
        (arr[i])->row   = pIndex->data.row;
        (arr[i])->value = pIndex->data.value;
        pIndex = pIndex->next;
    }
     return *arr;
}

我可以在第一次迭代中插入,但我在 VS19 中抛出了一个异常。 这就是我传递参数的方式:

*arr = createThreeArr(arr,head,counter); 

这些是结构体:

typedef struct Three 
{
  int value;
  int row;
  int col;
}Three;

typedef struct ListThree
{
  struct Three data;
  struct List* next;
}ListThree;

这是我的“主要”

void Ex3()
{ 
    Three* arr = NULL;
    ListThree* head = NULL;
    createArrayAndList(matrix,rows,cols,&head,&arr);
}

这个函数createArrayAndList:

int createArrayAndList(int** matrix,int rows, int cols, ListThree** head, Three** arr)
{
    int i, j, counter = 0;
    Three three;

    for (i = 0; i < rows; i++)
    {
        for (j = 0; j < cols; j++)
        {
            if (matrix[i][j] == i + j)
            {
                counter++;
                three = createThree(matrix[i][j],i,j);
                *head = createThreeList(head,three);
            }
        }
    }
    *arr = createThreeArr(arr,head,counter);

    return counter;
}

谢谢大家,如果您希望我提供更多信息,请告诉我。 我希望这不是一个愚蠢的问题。 :(

【问题讨论】:

  • 以及 createArrayAndList 是什么?
  • 嘿布鲁诺,我已经添加了你要求的功能。
  • createThreecreateThreeLIst 也不见了。在 Ex3 matrix,rowscols 中指的是全局变量?它们是如何定义和初始化的?
  • 我不想超出与我的问题无关的不必要的代码,但是矩阵输入发生在不同的函数中并且工作正常。唯一的问题仍然是函数 createThreeArr() 的输入。从 createThreeArr() 返回数组的正确方法是什么?
  • 是的,但问题可能出在隐藏代码中。无论如何,我在 createThreeArr 中发现了一个问题

标签: c arrays pointers struct linked-list


【解决方案1】:

拥有

typedef struct ListThree
{
  struct Three data;
  struct List* next;
}ListThree;

Three* createThreeArr(Three** arr, ListThree** head, int counter)
{
    int i = 0;
    ListThree* pIndex = *head;

createThreeArr中赋值

 pIndex = pIndex->next;

无效,因为 pIndex-&gt;next 的值是 struct List* 而不是 ListThree*

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2023-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-29
    相关资源
    最近更新 更多