c - 返回值3221225725,可能缓冲区溢出?

标签 c arrays pointers

练习的目的是分配“n”个维度从 2 到 n+1 的数组,并为每个数组的每个元素赋予随机值 所以我的想法是使用双指针指向指针(在某种程度上可以被视为数组(?))对不起意大利语,但这是我学校的练习 无论如何,该代码理论上似乎是正确的,但它不能执行超过 2 个周期,例如,它适用于 n=1,2 但从 3 开始,它退出周期并终止程序,有任何建议可以避免它或?

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAX 100

/*The aim of the exercise is to allocate "n" arrays whose dimensions goes from 2 to n+1 and give them random values to each element of each array
So my idea was to use double pointers to pointers (that can be considered arrays in some way (?) ) Sorry for the italian language but it's an exercise for my school
Anyhow, the code seems teorically correct but it can't do more than 2 cycles, for example it works for n=1,2 but from 3 and on it quits from the cycle and terminates the program, any suggestions?*/

int main() {
        int n, i, j = 0, array[MAX];
        int *p1 = NULL, **p2 = NULL;
        srand(time(NULL));
        printf("Inserisci un numero naturale n per allocare un numero n di vettori\ndi lunghezza da 2 a n+1 :\n"); //Write a natural number n to allocate n arrays which contains from 2 to n+1 elements
        scanf("%d", &n);
        printf("\n\n");
        p2 = (int**)malloc(n*sizeof(int*)); //allocating the space for a double pointer
        for (i = 2; i <= n+1; i++) {
                *p2 = (int*)malloc(i*sizeof(int)); //allocating the space for the pointers
                printf("\nVettore #%d = ", i-1);
                for (j = 0 ;j < i ;j++) {
                        p2[i-2][j] = rand() % 10;
                        printf("%d ", p2[i-2][j]);

                }
                free(*p2);
        }



return 0;


}

最佳答案

问题就出在这里。

*p2 = (int*)malloc(i*sizeof(int)); //allocating the space for the pointers

您想要创建一个“数组的数组”,这就是您使用双指针的原因。 int** p2 是指向 int* 的指针数组,即整数指针。

所以这看起来不错:

p2 = (int**)malloc(n*sizeof(int*)); //allocating space for an array of pointers

它是一个由 n 个指向 int* 的指针组成的数组。现在我们希望这些指针中的每一个都指向数组。在 for 循环中,使用

p2[i-2] = (int*)malloc(i*sizeof(int)); //allocating space for one array

这应该按您的预期工作。就个人而言,我会在循环中使用 ii+2,但您的选择没问题。

请注意,您不需要释放分配的内存。当你的程序结束时它就会消失。如果您的作业需要释放空间,那么您需要编写另一个循环来释放每个p2[i]数组中的内存,然后释放 p2.

此外,它被认为是 bad idea转换 malloc() 的返回值。

关于c - 返回值3221225725,可能缓冲区溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26823346/

相关文章:

c - 查看是否已抽取号码

c - 如何在C中仅执行cat

c++ - 在 C++ 中将字符存储到字符串中

c++ - 为什么我可以通过指针访问私有(private)数据成员,我应该这样做吗?

c - 从地址访问数据

html - 如何在 Code::block IDE 中将 HTML 嵌入到 C 代码中?

c - 指向结构的指针数组,调试时只有 SIGSEGV

c++ - lParam 或 WCHAR[] 有问题

c - 我如何在 c 中使用 fork() 对一个包含 2 个子项的数组进行排序

C - 当未转换为其类型的指针时,数组名称是什么?