該練習的目的是分配尺寸從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;
}
最好是使用可用的格式選項將代碼粘貼到問題中。 – ArjunShankar 2014-11-08 23:49:37
'p2 [i-2]'不好。 – BLUEPIXY 2014-11-08 23:53:13
您爲* p2分配多次空間。這與爲p2 [0]分配空間相同。但是你從來沒有爲i> 0分配p2 [i]的空間。只要將行'* p2 = malloc ...'改成'p2 [i-2] = ...' – 2014-11-09 00:04:05