c - 为什么我无法打印存储在创建的数组中的值?

标签 c arrays pointers matrix

因此用户可以创建他的方阵并输入所需的值。问题是矩阵是通过函数创建的,似乎当函数完成其任务时,我们返回主函数,我尝试重新打印矩阵的元素,以检查在第一次在函数内部打印,程序崩溃了。请记住,我仅使用指针而不是 []。此外,大小变量将在检查矩阵的各种属性(稀疏等)的函数中使用,这就是我这样使用它的原因。

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

int CreateArray(int **ptr);

int main()
{
    int **ptr = NULL;
    int size = 0;
    int i,j;

    size = CreateArray(ptr);

     for(i=0;i<size;i++)
    {
        for(j=0;j<size;j++)
        {
            printf("%d",*(*(ptr+i)+j));
            if(j == (size-1))
            {
                printf("\n");
            }
        }
    }




    system("PAUSE");
    return 0;
}


int CreateArray(int **ptr)
{
    int i=0;
    int j=0;
    int size = 0;

    printf("Input the size of your square matrix\n");
    scanf("%d", &size);

    ptr = malloc(sizeof(int*)*size);

    for(i=0; i< size; i++)
    {
        *(ptr + i) = malloc(sizeof(int)*size);
    }

    printf("Enter the values to be stored in your array\n");
    for(i=0;i<size;i++)
    {
        for(j=0;j<size;j++)
        {
            scanf("%d", &*(*(ptr+i)+j));
        }
    }

    for(i=0;i<size;i++)
    {
        for(j=0;j<size;j++)
        {
            printf("%d",*(*(ptr+i)+j));
            if(j == (size-1))
            {
                printf("\n");
            }
        }
    }

    return size;

}

最佳答案

您的指针是按值传递的。如果要从函数内部进行修改,则需要传递其地址。然后,您需要重新调整 CreateArray 中访问 ptr 的所有行以再次取消引用它:

int main()
{
    int **ptr = NULL;
    int size = 0;
    int i,j;

    size = CreateArray(&ptr);

    for(i=0;i<size;i++)
    {
        for(j=0;j<size;j++)
        {
            printf("%d ",*(*(ptr+i)+j));
            if(j == (size-1))
            {
                printf("\n");
            }
        }
    }

    return 0;
}


int CreateArray(int ***ptr)
{
    int i=0;
    int j=0;
    int size = 0;

    printf("Input the size of your square matrix\n");
    scanf("%d", &size);
    *ptr = malloc(sizeof(int*)*size);

    for(i=0; i< size; i++)
    {
       *((*ptr) + i) = (int*)malloc(sizeof(int)*size);
    }

    printf("Enter the values to be stored in your array\n");
    for(i=0;i<size;i++)
    {
        for(j=0;j<size;j++)
        {
            scanf("%d", (*((*ptr)+i)+j));
        }
    }

    return size;
}

关于c - 为什么我无法打印存储在创建的数组中的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22212963/

相关文章:

c - 在 for 语句中声明变量时出错

arrays - Flash AS3,如何使用整数键索引 HashMap

java - 如果字符串中包含较小的单词,如何将其拆分为两个标记

c++ - 使用 apr_shm 库指向结构体中的指针

c++ - 如何通过const对象中的指针使对象成为常量?

c - 如果使用 C 中的位运算,整数中的任何位等于 1,则返回 1

c - 在一个头文件中定义结构并在另一个头文件中使用它时出现结构错误

c - 循环无法识别变量?

ruby - 如何以表格格式快速打印 Ruby 哈希值?

c++ - (指针)在降低测试分数后计算平均函数的问题