首页 > 解决方案 > 在 main 外部和 main 内部分配全局结构变量

问题描述

问题是当我将代码分成不同的函数时,就会发生这种情况

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

//------Options -- change only true / false to trigger the function
bool hard_trace = false;
bool trace = true;
/*-------------------*/

//---------Defines----------
#define MAXSIZE 100 // maximum size of the characters in txt file to be buffed
/*----------------------*/

//---------Structs-----------
struct Matrix
{
    char *A[10];
    int depth;
};
/*--------------------------*/
//-----Variable----------
//-- global
char *B[3];
//- struct
struct Matrix matrixs ; // create new global struct
//-
//--
/*-----------------------*/

int convertCharToNumber(char target[1])
{
    int numbered = target[0] - 48;
    return numbered;
}

int generateDataFromFile(){
    //-- temped
    int currentLine = 1;
    int currentRow = 0;
    //-----------------
    FILE *fp;
    char line[MAXSIZE];

    fp = fopen("test.txt", "r");
    if (fp == NULL)
    {
        fprintf(stderr, "%s\n", "Error reading from file");
        exit(EXIT_FAILURE);
    }

    while (fgets(line, MAXSIZE, fp) != NULL)
    {
        if(hard_trace){ // if it was enabled
            printf("current line : %d and length : %d\n", currentLine, strlen(line));
        }
        if (line[strlen(line) - 1] == '\n') // cutout the \n to make the txt easy to use
        {
            line[strlen(line) - 1] = '\0';
        }
        //appileToStruct(line,currentRow);
        matrixs.A[currentRow] = line;
        //if(trace) printf("%s\n", line);
        currentLine++; currentRow++;
    }
    if(trace) printf("Total line receive from txt file : %d\n" , currentLine-1); //if it was enabled
    fclose(fp);

    // ----------- assign the var
    matrixs.depth = currentLine - 1;
    //----------------------------

    //return 1;
}

void main(){
    generateDataFromFile();
    printf("Total : %d TXT : [%s]", strlen(matrixs.A[0]), matrixs.A[0]);
}

和这里的输出

从 txt 文件接收的总行数:3

总计 : 10 TXT : []

.

但是当我像这样直接将代码放在main中时就可以了

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>

//------Options -- change only true / false to trigger the function
bool hard_trace = false;
bool trace = true;
/*-------------------*/

//---------Defines----------
#define MAXSIZE 100 // maximum size of the characters in txt file to be buffed
/*----------------------*/

//---------Structs-----------
struct Matrix
{
    char *A[10];
    int depth;
};
/*--------------------------*/
//-----Variable----------
//-- global
char *B[3];
//- struct
struct Matrix matrixs; // create new global struct
//-
//--
/*-----------------------*/

int convertCharToNumber(char target[1])
{
    int numbered = target[0] - 48;
    return numbered;
}

int main()
{
    //-- temped
    int currentLine = 1;
    int currentRow = 0;
    //-----------------
    FILE *fp;
    char line[MAXSIZE];

    fp = fopen("test.txt", "r");
    if (fp == NULL)
    {
        fprintf(stderr, "%s\n", "Error reading from file");
        exit(EXIT_FAILURE);
    }

    while (fgets(line, MAXSIZE, fp) != NULL)
    {
        if (hard_trace)
        { // if it was enabled
            printf("current line : %d and length : %d\n", currentLine, strlen(line));
        }
        if (line[strlen(line) - 1] == '\n') // cutout the \n to make the txt easy to use
        {
            line[strlen(line) - 1] = '\0';
        }
        //appileToStruct(line,currentRow);
        matrixs.A[currentRow] = line;
        //if(trace) printf("%s\n", line);
        currentLine++;
        currentRow++;
    }
    if (trace)
        printf("Total line recieve from txt file : %d\n", currentLine - 1); //if it was enabled
    fclose(fp);

    // ----------- assign the var
    matrixs.depth = currentLine - 1;
    //----------------------------

    printf("Total : %d TXT : [%s]", strlen(matrixs.A[0]), matrixs.A[0]);
}

输出

从 txt 文件接收的总行数:3

总计:10 TXT:[0000111100]

你能向我解释为什么第一个代码不起作用我的意思是为什么 printf 中的 %s 没有为我显示输出,我怎样才能让第一个代码起作用

标签: cstructmain

解决方案


这就是为什么:matrixs.A[currentRow] = line;

line在第一种情况下是函数的局部。该语句分配了指针,它不会复制字符串(您应该使用strncpy,并且不要忘记分配所需的内存空间malloc),因此当所有内容都在main(),line在该范围内定义良好时,matrixs.A[0]指向在第一种情况下存在line的行是属于 generateDataFromFile() 的本地数组。

当您尝试matrixs.A[0]main()(在第一种情况下)打印时,您会调用未定义的行为,因为您正在执行堆栈违规并尝试访问堆栈上的某个地址,该地址可能包含您在流程执行时想要的任何内容。

建议修复:

// instead of matrixs.A[currentRow] = line
size_t lineSize = strlen(line)+1;
matrixs.A[currentRow] = malloc(lineSize);
strncpy(matrixs.A[currentRow], line, lineSize);

并且不要忘记free()最后分配的内存。


推荐阅读