2014-11-08 1849 views
-1

该练习的目的是分配尺寸从2到n + 1的“n”个数组,并将它们的随机值赋予每个数组的每个元素 所以我的想法是使用双指针指向指针(可以考虑数组以某种方式(?))对不起意大利语言,但它是我的学校的练习 无论如何,代码看起来是正确的,但它不能超过2个周期,例如它适用于n = 1,2但是从3开始并退出循环并终止程序,有什么建议可以避免它或?返回值3221225725,可能的缓冲区溢出?

下面的代码:

#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; 


} 
+1

最好是使用可用的格式选项将代码粘贴到问题中。 – ArjunShankar 2014-11-08 23:49:37

+1

'p2 [i-2]'不好。 – BLUEPIXY 2014-11-08 23:53:13

+1

您为* p2分配多次空间。这与为p2 [0]分配空间相同。但是你从来没有为i> 0分配p2 [i]的空间。只要将行'* p2 = malloc ...'改成'p2 [i-2] = ...' – 2014-11-09 00:04:05

回答

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,但您的选择是好的。

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

另外,它被认为是bad idea来从malloc()投下返回值。

+0

非常感谢!你的回答是完美而快速的。它解决了我的问题。我会记住你的建议。 – 2014-11-09 01:04:28