[英]How to fix "Segmentation Fault" in this case
我想制作一个程序,读取带有一方信息的字符串,将“/”之间的信息分开,然后使用该信息创建一个对象。
我做了一个cicle,如图所示。 如果我只想打印它,它工作正常,但是当我尝试将它分配给变量时,就会发生错误 - Segmentation Fault
我的结构如下:
typedef struct {
char description[40];
int date;
int time;
int duration;
int room;
char parent[40];
char kids[3][40]
} Party;
读取字符串的函数是:
void createParty():
Party p;
char s[LIMIT] = "John's Birthday/25032019/2230/10/1/Thomas/Anna/Jack/Sarah";
char c[2] = "c";
char *token;
int i=0;
token = strtok(str, s);
while( token != NULL ) {
printf( " %s\n", token );
token = strtok(NULL, s);
if (i==0)
strcpy(p.description,token);
else if (i==1)
p.date=atoi(token);
else if (i==2)
p.time=atoi(token);
else if (i==3)
p.duration=atoi(token):
else if (i==4)
p.room=atoi(token);
else if (i==5)
strcpy(p.parent,token);
else
strcpy(p.kids[j-6],token);
i++
}
我希望分配所有值都没有问题,但是当我尝试分配最后一个孩子时,它给了我Segmentation Fault 。 如果我不尝试分配姓氏,则不会出现错误。
谢谢!
以下建议代码:
i
的多重测试function to call the
createParty()”函数createParty()
MAX_PARTIES
更改为 1 以外的值strtok()
,因此打印了第一次调用strtok()
的结果,但从未处理到结构中现在,建议的代码:
#include <stdio.h> // printf()
#include <string.h> // strtok(), strncpy()
#include <stdlib.h> // atoi()
#define LIMIT 500
#define MAX_PARTIES 1
#define MAX_DESC_LEN 40
#define MAX_PARENT_LEN 40
#define MAX_KIDS 3
#define MAX_KID_LEN 40
struct PARTY
{
char description[ MAX_DESC_LEN ];
int date;
int time;
int duration;
int room;
char parent[ MAX_PARENT_LEN ];
char kids[ MAX_KIDS ][ MAX_KID_LEN ]; // was missing trailing semicolon
};
typedef struct PARTY MyParty;
// prototypes
void createParty( void ); // notice 'void' parameter in prototype
void createParty() // removed extranious trailing char
{
MyParty p[ MAX_PARTIES ]; // Note: a 2 space indent level can be 'lost' with variable width fonts
char s[LIMIT] = "John's Birthday/25032019/2230/10/1/Thomas/Anna/Jack/Sarah";
char delimiters[] = "//"; // note using '//' as first slash 'escapes' the second slash
int i=0;
char * token = strtok( s, delimiters );
while( token && i < 11 )
{
printf( "%s\n", token );
switch( i )
{
case 0:
strncpy( p[i].description, token, MAX_DESC_LEN-1 );
break;
case 1:
p[i].date = atoi( token );
break;
case 2:
p[i].time = atoi( token );
break;
case 3:
p[i].date = atoi( token );
break;
case 4:
p[i].duration = atoi( token );
break;
case 6:
p[i].room = atoi( token );
break;
case 7:
strncpy( p[i].parent, token, MAX_PARENT_LEN-1 );
break;
case 8:
strncpy( p[i].kids[0], token, MAX_KID_LEN-1 );
break;
case 9:
strncpy( p[i].kids[1], token, MAX_KID_LEN-1 );
break;
case 10:
strncpy( p[i].kids[2], token, MAX_KID_LEN-1 );
break;
default:
printf( "unexpected field found: %s\n", token );
break;
}
i++; // was missing trailing semicolon
token = strtok( NULL, delimiters ); // prep for next loop iteration
} // end switch
} // end function: createParty()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.