2014-11-08 1850 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