gpt4 book ai didi

c - 转换代码中的段错误(核心转储)错误

转载 作者:行者123 更新时间:2023-11-30 21:11:11 24 4
gpt4 key购买 nike

我是 C 编程新手,面临以下代码片段的段错误。sample.txt 用作文件输入,下面是该文件的内容。

以下是sample.txt文件的内容-

          1001:"field1":N
1001:"field2":B
1001:"field3":A
1001:"field4":D
1001:"field5":N
1001:"field6":N

这在我的代码片段中-

#include <string.h>
#include<stdio.h>
#include<stdint.h>
#include<stdlib.h>
#define MAX_OID_LEN 128
#define MAX_FILE_NAME_LEN 128
#define MAX_BUFFER_SIZE 80
#define MAXSTRINGSIZE 20
#define MAX_VALUE_LEN 128
int8_t* field[MAX_VALUE_LEN]={0,};

int8_t* type[MAX_VALUE_LEN]={0,};
int8_t field_count=0;
char * option(int8_t* type[MAX_VALUE_LEN], int8_t* field[MAX_VALUE_LEN])
{

int8_t i=0;
if(*type)
{
while(**type)
{
switch(**type)
{

case 'D':

printf("\nDateType");
printf("\nfield=%s",field[i]);
break;
case 'N':
printf("\nInteger");
printf("\nfield=%s",field[i]);
break;
case 'A':
printf("\nAscii");
printf("\nfield=%s",field[i]);

break;
case 'B':
printf("\nBinary");
printf("\nfield=%s",field[i]);

break;

default:
printf("\nDefault=%s",field[i]);
return *type;
//break;
}
*type++;
i++;
printf("\ni=%d",i);
}
printf("%s",field[i]);

}
return NULL;

//printf("%s",field[i]);
}


int main()
{
int8_t field_count=0;
int8_t* data_field;
int8_t* token;
int8_t* ismp_field;
int8_t *search = ":";
FILE *fp;
int8_t* filename = "sample.txt";
fp = fopen ( filename, "r" );
if( fp != NULL )
{
int8_t line [MAX_BUFFER_SIZE];
while ( fgets ( line, sizeof (line), fp ) != NULL )
{
token = strtok( line, search );
ismp_field = strtok( NULL, search );
data_field = strtok( NULL, "\n" );
if(ismp_field!=NULL)
{
field[field_count]=strdup(ismp_field);
printf("\nismp_field=%s\n", ismp_field);
type[field_count]=strdup(data_field);
printf("\ndata_value=%s\n",type[field_count]);
field_count++;
}
}
fclose ( fp );


}
char *val=option(type,field);
printf("%s",val);
return 1;
}

最佳答案

关于 option 函数内 type 的取消引用,这可能就是您的问题所在。因为你将它声明为一个指针数组,并且每个指针都被初始化为 NULL,然后你取消引用这些 NULL 指针,这就导致 undefined behavior和你的崩溃。

关于c - 转换代码中的段错误(核心转储)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25094988/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com