2017-05-29 67 views
-1

我试图让这个工作,但我不断得到真正的奇怪的错误,有时它执行没有错误,有时我得到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的错误,其他时候它崩溃后输出。绝对没有丝毫的线索为什么。

+2

请记住,你传递给大小['malloc'(http://en.cppreference.com/w/c/memory/malloc)是它的大小应该分配*字节*,而不是元素。 –

+0

旁注:不能以C返回数组。您将指针**返回给第一个元素**。 – Olaf

回答

6

您预留空间len字节,但要保留空间

int * gene = malloc(sizeof(int) * len); 

int * gene = malloc(sizeof(*gene) * len); 

你忘了#include <time.h>

+1

它给了一个编译错误,但我现在只是看到你的错字 – vonlolzor

+1

现在完美的作品!谢谢! – vonlolzor

+1

接受@KeineLust的回答 –

0

使用malloc直接过无错误俯卧;在你的代码中,你忘记了与元素大小相乘。

使用宏来代替:

#define NEW_ARRAY(ptr, n) (ptr) = malloc((n) * sizeof (ptr)[0]) 

int *gene; 
NEW_ARRAY(gene, len); 
+1

嗯,这是非常整洁,谢谢! – vonlolzor