有关整数三重指针和浮点三重指针的区别的问题

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

我正在做一个学校的项目,他们强迫我们在将两个矩阵相乘的函数中使用类型float三重指针,在最后一天,我不知道为什么当我使用整数三重指针时,我得到了所需的数字,但是当我使用浮点数时,我得到了零。我写了一些简单的例子来解决这个问题。谢谢!!

    int ***ptr3;
    int Matrix[3][3] = { {1,2,3},{4,5,6},{7,8,9} };
    int i;

    ptr3 = malloc(sizeof(int));
    ptr3 = Matrix;
    for (i = 0; i < 9; i++) {printf_s("%d ", ptr3[i]);}


    printf_s("\n");


    float ***ptr3_f;
    float Matrix_f[3][3] = { {1,2,3},{4,5,6},{7,8,9} };

    ptr3_f = malloc(sizeof(float));
    ptr3_f = Matrix_f;
    for (i = 0; i < 9; i++) {printf_s("%.1f ", ptr3_f[i]);}

enter image description here

c arrays pointers matrix integer
2个回答
0
投票

您不需要此类数组的三重指针。

使用:

#include <stdio.h>

#include <stdlib.h>

int main()
{

    int *ptr3_i;
    int Matrix[3][3] = { {1,2,3},{4,5,6},{7,8,9} };

    float *ptr3_f;
    float Matrix_f[3][3] = { {1,2,3},{4,5,6},{7,8,9} };

    int i;

    ptr3_i = (int *)Matrix;
    printf("ptr3_i:");
    for (i = 0; i < 9; i++) 
        printf("%d ", ptr3_i[i]);
    printf("\n");

    ptr3_f = (float *)Matrix_f;
    printf("ptr3_f:");
    for (i = 0; i < 9; i++) 
        printf("%.1f ", ptr3_f[i]);
    printf("\n");

    return 0;
}

我得到:

ptr3_i:1 2 3 4 5 6 7 8 9 
ptr3_f:1.0 2.0 3.0 4.0 5.0 6.0 7.0 8.0 9.0 

0
投票

编译代码时看到警告了吗:

警告:来自不兼容指针类型[-Wincompatible-pointer-types]的分配

警告:格式为'%d'的参数应为类型'int',但参数2的类型为'int **'[-Wformat =]来自不兼容的指针类型[-Wincompatible-pointer-types]

的赋值

警告:格式为'%f'的参数应为'double'类型,而参数2的类型为'float **'[-Wformat =]

您可以执行以下操作:

ptr3 = malloc(sizeof(int**));
*ptr3 = malloc(sizeof(int*));
**ptr3 = Matrix[0]; // point to first row of the matrix

ptr3_f = malloc(sizeof(float**)); // allocate the memory for storing one double pointer
*ptr3_f = malloc(sizeof(float*)); // allocate the memory for storing one single pointer
**ptr3_f = Matrix_f[0]; // point to first row of the matrix
© www.soinside.com 2019 - 2024. All rights reserved.