我有一个一维数组,其中ive初始化为0,但由于某种原因,当我进入一个循环,并试图将其内容增加1时,位置0的值保持恢复为0,即使我将其增加1。
#include <stdio.h>
#include <stdlib.h>
#define TOTAL_V 3
#define NUM_CANDIDATES 7
int hex_age(unsigned short hex){
unsigned short age = hex >> 9;
if (age >18 && age <101)
return age;
else return 0;
}
int hex_gender(unsigned short hex){
unsigned short gender = hex >> 7 & 3;
return gender;
}
int hex_vote(unsigned short hex){
unsigned short vote, tmp = hex & 0x7f , count = 0;
if (tmp == 0)
return 7;
for (int i = 0 ; i<7; i++){
if (tmp & 1 == 1){
count++;
vote = i;
}
tmp = tmp >> 1;
}
if (count > 1)
return 7;
return vote;
}
int main() {
int s_votes = 0, f_votes = 0, v_count[NUM_CANDIDATES] = {0};
unsigned short **v_info, hex_v_info , age , gender , vote;
FILE *fp;
fp = fopen("data1.dat" , "r");
if (fp == NULL){
fprintf(stderr ,"apotuxe o anoigmos tou arxeiou");
exit(-1);
}
if (feof(fp)){
fprintf(stderr, "to arxeio einai adeio");
exit(-1);
}
while (fscanf(fp ,"%x", &hex_v_info) != EOF){
age = hex_age(hex_v_info);
if(age == 0)
f_votes++;
else {
gender = hex_gender(hex_v_info);
if (gender == 0)
f_votes++;
else{
vote = hex_vote(hex_v_info);
if (vote == 7)
f_votes++;
else{
if (s_votes == 0){
v_info = malloc(sizeof(int *));
v_info[s_votes] =malloc(sizeof(int)* TOTAL_V);
}
else{
v_info = realloc(v_info , sizeof(int *)*(s_votes+1));
v_info[s_votes] = malloc(sizeof(int)*TOTAL_V);
}
v_info[s_votes][0] = age;
v_info[s_votes][1] = gender;
v_info[s_votes][2] = vote;
v_count[vote]++;
s_votes++;
}
}
}
}
fclose(fp);
for (int i = 0; i<s_votes; i++)
free(v_info);
return 0;
}
由于某种原因,当我使用calloc创建数组时,它没有这个问题,有人知道为什么会发生这个问题吗
1条答案
按热度按时间sd2nnvve1#
1.您声明了
unsigned short hex_v_info
(在我的系统中为2个字节),然后使用fscanf(fp ,"%x", &hex_v_info)
从读取数据,其中格式字符串%x
期望int的地址(在我的系统中为4个字节)。unsigned short **v_info
但是你存储了一个int [s_votes]
的数组。如果你的指针不一致,这将是一个问题。realloc(NULL, 1)
定义得很好,所以只要用它来代替malloc() of the first element. You need to assign the result of
realloc()'到一个临时变量,就可以处理NULL。否则会丢失数据和内存泄漏。1.如果s_votes〉1,
free(v_info);
会导致释放两次,并且仍然会泄漏在v_info[i]
上分配的内存。和输入文件file:
它似乎正确处理信息数据: