我想制作一个程序,用一方的信息读取一个字符串,在“/”之间分隔信息,然后用信息创建一个对象。
我做了一个cicle,如网页所示。如果我只想打印它,它工作正常,但当我尝试将其分配给变量时,错误发生 - 分段错误
我的结构如下:
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++
}
我期望所有的值都会被分配没有问题,但是当我尝试分配最后一个孩子时,它会给我分段错误。如果我不尝试分配姓氏,则没有错误。
发布于 2019-03-26 09:50:51
以下提议的代码:
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()
https://stackoverflow.com/questions/-100008990
复制相似问题