2017-05-29 40 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