我試圖讓這個工作,但我不斷得到真正的奇怪的錯誤,有時它執行沒有錯誤,有時我得到memory access violation
錯誤,7返回的值總是garbage
並且有一個printf
該程序由於某種原因而無法使用。我對C
不擅長,所以我沒有絲毫的線索。在C中返回數組:隨機錯誤,垃圾值
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
int gen_bp() {
int min = 0;
int max = 3;
int r;
r = (rand() % (max + 1 - min)) + min;
return r;
}
int * gen_gene(int len) {
int a;
int * gene = malloc(len);
int bp;
srand((unsigned)time(NULL));
for(a = 0; a < len; a = a + 1){
bp = gen_bp();
printf("value of a: %i\n", bp); //if i remove this line, it crashes?!
gene[a] = bp;
}
return gene;
}
int main()
{
char codons[4] = {'G','T','A','C'};
int genelen = 20;
int counter;
int * gene;
gene = gen_gene(genelen);
for(counter = 0; counter < genelen; counter++){
printf("%i value of a: %i\n", counter, gene[counter]);
}
free(gene);
return(0);
}
這是輸出我得到
value of a: 1
value of a: 1
value of a: 3
value of a: 0
value of a: 2
value of a: 1
value of a: 3
value of a: 3
value of a: 1
value of a: 2
value of a: 3
value of a: 0
value of a: 3
value of a: 1
value of a: 0
value of a: 2
value of a: 3
value of a: 2
value of a: 2
value of a: 0
0 value of a: 1
1 value of a: 1
2 value of a: 3
3 value of a: 0
4 value of a: 2
5 value of a: 1
6 value of a: 3
7 value of a: 3
8 value of a: 1
9 value of a: 2
10 value of a: 1635131449 // 10 to 16 are always garbage, and never change
11 value of a: 1702194273
12 value of a: 543584032
13 value of a: 891304545
14 value of a: 808661305
15 value of a: 892351281
16 value of a: 2570
17 value of a: 2
18 value of a: 2
19 value of a: 0
有時它最終罰款爲0的錯誤,其他時候它崩潰後輸出。絕對沒有絲毫的線索爲什麼。
請記住,你傳遞給大小['malloc'(http://en.cppreference.com/w/c/memory/malloc)是它的大小應該分配*字節*,而不是元素。 –
旁註:不能以C返回數組。您將指針**返回給第一個元素**。 – Olaf