即使正确初始化,C结构也会打印错误的值
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了即使正确初始化,C结构也会打印错误的值相关的知识,希望对你有一定的参考价值。
在下面的程序中,即使我将垃圾值获取到结构成员之一,我仍在正确分配用于指针的内存,然后正确分配各个指针并正确设置值。我不明白我到底要去哪里。
下面程序的示例输出是:
***CK: H2 nSupport: 0
CK: H2 nSupport: 1303643608
CK: FR2 nSupport: 0
CK: H2 nSupport: 1303643608
CK: FR2 nSupport: 0
***CK: SP2 nSupport: 0
我不理解我如何获得值1303643608,尽管它在一开始就设置正确。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NOK 15
#define ML 100
typedef struct sample_test_for_ties_t
char sender[NOK];
char receiver[NOK];
char message[ML];
sample_test_for_ties;
typedef struct CUOfS_t
char cK[NOK];
char eK[NOK];
char nK[NOK];
char AL[ML];
int nSupport;
CUOfS;
CUOfS **Btenders = NULL;
sample_test_for_ties test_ties[] =
"H2","ICY", "fmaabghijklmmcdenoopqrstuvwxyz",
"FR2","AIY", "fmaabghijklmmcdenoopqrstuvwxyz",
"SP2","LAY", "fmaabghijklmmcdenoopqrstuvwxyz",
"H30","ICY", "fmaabghijklmmcdenoopqrstuvwxyz",
"F30","AIY", "fmaabghijklmmcdenoopqrstuvwxyz",
"W30","LAY", "fmaabghijklmmcdenoopqrstuvwxyz",
;
void InitBtenders(int numOfBCtenders)
int count =0;
if(!Btenders)
if(Btenders = (CUOfS **)malloc(sizeof (**Btenders) * numOfBCtenders))
while(count < numOfBCtenders)
Btenders[count] = NULL;
count++;
else
printf("Malloc failed\n");
void freeBtenders(int numOfBCtenders)
int count =0;
if(Btenders)
while(count<numOfBCtenders)
if(Btenders[count])
free(Btenders[count]);
Btenders[count] = NULL;
count++;
free(Btenders);
Btenders = NULL;
void UpdateBtendersInfo(char *aContenders)
static int counter =0;
if(Btenders)
if(Btenders[counter] == NULL)
Btenders[counter] = (CUOfS *)malloc(sizeof (Btenders[counter]));
if(Btenders[counter])
strcpy(Btenders[counter]->cK,aContenders);
strcpy(Btenders[counter]->eK,"\0");
strcpy(Btenders[counter]->nK,"\0");
memset(Btenders[counter]->AL,0,sizeof(Btenders[counter]->AL));
Btenders[counter]->nSupport = 0;
counter++;
else
printf("Insufficient memory for Btender\n");
else
printf("Looks like memory not allocated for Btenders\n");
int count =0;
while(count <counter && Btenders[count])
printf("***CK: %s nSupport: %d\n",Btenders[count]->cK,Btenders[count]->nSupport);
count++;
printf("\n");
int main()
int numOfBCtenders = 3;
int noc =0;
InitBtenders(numOfBCtenders);
while(noc < numOfBCtenders)
UpdateBtendersInfo(test_ties[noc].sender);
noc++;
freeBtenders(numOfBCtenders);
return 0;
我希望
***CK: H2 nSupport: 0
但是我得到
***CK: H2 nSupport: 1303643608
答案
为Btenders
分配内存的方式不正确。
以上是关于即使正确初始化,C结构也会打印错误的值的主要内容,如果未能解决你的问题,请参考以下文章