c - 在 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 没有为我显示输出,我怎样才能让第一个代码起作用
解决方案
这就是为什么: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()
最后分配的内存。
推荐阅读
- python - 每当我设置初始速度 0、最终速度 10 和时间变化 10 时,我都会得到 50 的回报
- c++ - 我可以在不知道捕获的情况下完善转发 lambda 函数吗?
- r - 当数据存在于usmap包中时,为什么这些状态不显示数据?
- c# - 调用 VisualTreeHelper.GetChild() 时出现 ArgumentOutOfRangeException
- c++ - Wxwidgets || 添加类和方法
- amazon-web-services - 将当前 Redshift 模式导入 Redshift QA 环境
- javascript - 儿童道具事件不保持父母的当前状态
- python - 在选定索引处插入字符串的程序
- sql - 同时计算两列中的值?SQL/SQLITE
- javascript - 带有 mapbox 的传单 - 设置默认语言