我正在写一个计算信息熵的程序,这是熵(H)的函数
base 2 log is used here
然后这是我的程序
#include <stdio.h>
#include <math.h>
#include <stdlib.h>
#include <signal.h>
typedef struct vars {
char *var;
float prob;
} CHOISES;
float infocont(float x);
float entropy(CHOISES *, int);
void onsig(int);
int main(int argc, char *argv[])
{
int i = 0;
int siz = 0;
float H = 0.0;
printf("input the number of vars: ");
scanf("%d", &siz);
//printf("echo: %d\n", siz);
CHOISES chs[siz];
signal(SIGSEGV, onsig);
for (i = 0; i < siz; i++) {
printf("%d: ", i + 1);
scanf("%s %f", chs[i].var, &chs[i].prob); /* HERE IS THE ERROR */
//printf("echo: %s %f\n", chs[i].var, chs[i].prob);
}
H = entropy(chs, siz);
printf("Entropy is %f\n", H);
}
void onsig(int signo)
{
fprintf(stderr, "signal caught: %d\nSEGMENTATION FAULT\n", signo);
}
float infocont(float x)
{
return (log(1/x) / log(2));
}
float entropy(CHOISES chs[], int len)
{
short i;
float entropy;
for (i = 0; i < len; i++) {
entropy += chs[i].prob * infocont(chs[i].prob);
}
return entropy;
}
我的问题是,当我输入第一个输入并按回车键时,它会出现段错误。 我使用了调试器,发现为结构分配数据会导致段错误。 也就是这段代码行执行的时候
scanf("%s %f", chs[i].var, &chs[i].prob);
发生段错误。
但我想不出这段代码有什么错误。
为什么这个 scanf() 会产生段错误?
最佳答案
chs[i].var
是一个悬挂指针。您必须先为它malloc
内存。
chs[i].var = malloc(Max_str_len + 1); //<--- this
scanf("%s %f", chs[i].var, &chs[i].prob);
关于c - 为什么这个 scanf 会导致段错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34681323/