我试图让这个工作,但我不断得到真正的奇怪的错误,有时它执行没有错误,有时我得到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