意外初始化全局变量

时间:2015-05-07 13:38:23

标签: c linux pointers gcc initialization

我的头文件为:

test.h

//Mandatory fields size macro
#define size_uid   65
#define size_txn   33
#define size_adhaarNo 13
#define size_ver   4
#define size_input 65
#define size_photo 1024*1024*10
#define size_pseudonym 50
#define size_name 50

//Mandatory fields declaration
char uid[size_uid];
char txn[size_txn];
char adhaarNo[size_adhaarNo];
char ver [size_ver];
char *photo;
char pseudonym[size_pseudonym];
char name[size_name];
char input[size_input];
void incorrect_val_test(FILE *, FILE *, FILE *, FILE *, FILE *, FILE *,FILE *,FILE *,FILE *,FILE*);

test.c的

#include "test.h"

//Mandatory fields declaration
char uid[] = "865A80A01C70A9E0D5FC5F4D354A9155BF58CD483B1397C92614E5BC92317ACC";
char txn[] = "23da7b99-c561-4102-9df8-d37fbfe1";
char adhaarNo[] = "250241800087";
char ver [] = "1.0";
char *photo = (char *)malloc(sizeof(char)*size_photo);
char pseudonym[] = "2b6c55566d14459991513fb00bce34ed";
char name[] = "Amarjeet Sharma";
char input[] = "936a185caaa266bb9cbe981e9e05cb78cd732b0b3280eb944412bb6f8f8f07af";

void incorrect_val_test(FILE *ver, FILE *ts, FILE *txn, FILE *vtxn, FILE *uid, FILE *input, FILE *adhaarNo, FILE *photo, FILE *name, FILE *pseudonym)
{
       //Some initialization and files are opened here....

    photo = (char *)malloc(sizeof(char)*size_photo);

    FILE *photos = fopen("./input/data.txt","r");

    if(photos == NULL)
    {
        printf("Can't open data file.\n");
        return;
    }

    i=0;

    while((read_char = fgetc(photos))!= EOF)
    {
        if(read_char == '\n')
        continue;

        photo[i]= read_char;
        i++;    
    }


// Some more processing done here
}

的main.c

int main()
{

      // Some files are opened here to read data.
      incorrect_val_test(fp_ver, fp_ts, fp_txn, fp_vtxn, fp_uid, fp_input, fp_adhaarNo, fp_photo, fp_name, fp_pseudonym);

       return 0;
}

当我编译它时会出现以下错误消息

错误消息

  

警告:从不兼容的指针类型分配   [-Wincompatible-pointer-types]
photo =(char   *)malloc(sizeof(char)* size_photo);
错误:从类型'char'分配类型'FILE {aka struct _IO_FILE}'时不兼容的类型
  photo [i] = read_char;

有人能指出我哪里出错吗?

2 个答案:

答案 0 :(得分:4)

您可以进行类似

的功能调用
 char *photo = (char *)malloc(sizeof(char)*size_photo);

功能中。 global 范围内不允许这样做。删除全局,将incorrect_val_test()函数中的一个保留。

此外,请malloc() Cchar *photo = NULL;中的家人返回do not cast

解决方案:

  1. 在全球范围内定义photo
  2. 正如您所做的那样,将内存分配到incorrect_val_test()内的char *photo = malloc(size_photo); //cast not required // sizeof(char) is guranteed to be 1 ,例如

    FILE *photo
  3. 然后,您在函数参数列表中的incorrect_val_test()函数中有void incorrect_val_test(..., FILE *photo, ...)

    char * photo

    阴影全局 void incorrect_val_test(..., FILE *photos, ...) ^ |

    恕我直言,你想要的是写

     photos = fopen("./input/data.txt","r");
    

    ,在函数体内,

    photo

    但是,为什么要使用带有单个字符差异的变量名?使用更冗长,易于区分的东西。

    注意:使用free()完成后,请不要忘记onclick已分配的内存以避免内存泄漏。

答案 1 :(得分:3)

你有这个功能

void incorrect_val_test(..., FILE *photo, ...)

请注意,您有一个阴影全局变量的参数。这就是你在问题中出错的原因。