gpt4 book ai didi

c - 返回 C 中的数组 : random errors, 垃圾值

转载 作者:行者123 更新时间:2023-11-30 18:21:28 26 4
gpt4 key购买 nike

我正在尝试让它工作,但我不断收到非常奇怪的错误,有时它执行时没有错误,有时我收到内存访问冲突错误,返回值中的7个总是garbage 并且有一个 printf 由于某种原因程序无法使用。我不擅长 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 错误结束,有时则在输出后崩溃。绝对不知道为什么。

最佳答案

您正在为 len 预留空间字节,但您想为

保留空间
int * gene = malloc(sizeof(int) * len);

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

你忘了#include <time.h>

关于c - 返回 C 中的数组 : random errors, 垃圾值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44237814/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com