练习的目的是分配“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
这应该按您的预期工作。就个人而言,我会在循环中使用 i
和 i+2
,但您的选择没问题。
请注意,您不需要释放
分配的内存。当你的程序结束时它就会消失。如果您的作业需要释放
空间,那么您需要编写另一个循环来释放每个p2[i]
数组中的内存,然后释放 p2
.
此外,它被认为是 bad idea转换 malloc()
的返回值。
关于c - 返回值3221225725,可能缓冲区溢出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26823346/