【问题标题】:C - structures and listsC - 结构和列表
【发布时间】:2013-01-03 01:23:05
【问题描述】:

我想将两个数组的笛卡尔积保存到一个多维数组中。

arr[number][0] - 第一个数组中的数字
arr[number][1] - 第二个数组中的数字

number = sizeof(array1)*sizeof(array2)

int main() {
    int arr1[4] = {1, 4, 2, 3};
    int arr2[4] = {4, 1, 3, 3};
    int **outcomes = getProduct(arr1, 4, arr2, 4);

    int i;
    for(i = 0; i < 16; i++)
        printf("%d", outcomes[i][0]);

    getchar();
}

int* getProduct(int arr1[], int size1, int arr2[], int size2) {
    int **outcomes = (int *)malloc(sizeof(int)*16), count = 0, i, j;

    for(i = 0; i < size1; i++) {
        for(j = 0; j < size2; j++) {
            outcomes[count][0] = arr1[i];
            outcomes[count][1] = arr2[j];
            count++;
        }
    }
    return outcomes;
};

但是,这段代码在 getProduct() 函数内的嵌套循环中出现异常中断。逻辑没问题,我觉得问题可能出在指针上。

  1. 为什么需要用两个指针初始化多维数组?
  2. 为什么这段代码不起作用?
  3. 您对我如何改进此代码有什么建议吗? (我没有过多地用 C 编写代码,所以我不知道“好”代码使用哪种结构)。

【问题讨论】:

  • 这段代码甚至不应该编译。请务必注意编译器生成的警告/错误消息。
  • 你能帮我为这个二维数组分配内存吗? :P

标签: c arrays


【解决方案1】:

函数getProduct 将失败,因为您将指向int 的指针(即int*)分配给指向int 指针的指针(即int**)。

Why do I need to initialize multidimentional arrays with two pointers? 

因为

int**(指向 int 指针的指针)- 有了这个,我们可以访问任何行和任何列的元素,这是用单个指针(或一维数组)不可能实现的

int*** 类似地可用于三维数组,也就是指向 int 指针的指针

   To improve the code

我认为你的笛卡尔积函数应该是这样的

int** getProduct(int arr1[], int size1, int arr2[], int size2) {
    int **outcome = malloc(sizeof(int*)*size1);        
    int i,j;
    for(i = 0;i<size1;i++)
     outcome[i] = malloc(sizeof(int)*size2);
    for(i = 0; i < size1; i++) {
        for(j = 0; j < size2; j++) {
            outcome[i][j] = arr1[i] * arr2[j];
        }
    }
    return outcome;
}

你的 main() 像这样

int main() {
    int arr1[4] = {1, 4, 2, 3};
    int arr2[4] = {4, 1, 3, 3};
    int **outcomes = getProduct(arr1, 4, arr2, 4);

    int i,j;
    for(i = 0; i < 4; i++){
     for(j = 0;j <4; j++){
        printf("%d  ", outcomes[i][j]);
     }
     printf("\n");
    }
    getchar();
}

【讨论】:

  • *ptr 是干什么用的?它从未使用过。
  • @khernik 修改了答案,删除了不必要的 *ptr。这对你来说应该很好。 .
  • int**not 一个“数组数组”...参见例如c-faq.com/aryptr/pass2dary.html.
猜你喜欢
  • 2013-08-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-06-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-14
相关资源
最近更新 更多