如何将strtok()
中的值赋给结构中的数组?在我的结构中,我有char *extraRoomOne
,在我的主要内容中我有:
while (token!= NULL)
{
token = strtok(NULL, " ");
certainRoom.extraRoomOne[counter] = token;
}
编译器告诉我取消引用它,但是当我这样做时,我会遇到一个seg错误。
typedef struct room{
char *extraRoomOne;
}room;
在主要方面,我所拥有的只是'room certainRoom;
编辑:将char * extraRoomOne更改为char ** extraRoomOne
现在我有:
token = strtok(NULL," ");
certainRoom.extraRoomOne = realloc(certainRoom.extraRoomOne,(counter + 1) * sizeof(char *));
certainRoom.extraRoomOne[counter] = malloc(strlen(token)+1);
strcpy(certainRoom.extraRoomOne[counter],token);`
这是realloc和malloc的正确方法吗?我每次都在下面增加计数器
答案 0 :(得分:2)
您不应该执行该分配,因为strtok()
返回指向您在第一次调用中传递的字符串的指针,并且它将在后续调用中更改它,'\0'
终止符可以移动strtok()
终结符1}}所以指针将指向末尾的不同字符串,但您可以复制字符串,首先使用malloc()
然后使用strcpy()
size_t length;
length = strlen(token);
certainRoom.extraRoomOne = malloc(1 + length);
if (certainRoom.extraRoomOne != NULL)
strcpy(certainRoom.extraRoomOne, token);
你应该记得包括string.h
。
如果您真正想要的是捕获的不只是一个令牌,这可以解释while
循环,您可以这样做
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
typedef struct room{
char **tokens;
size_t count;
} room;
room
tokenizeString(char *string)
{
char *token;
room instance;
instance.tokens = NULL;
instance.count = 0;
token = strtok(string, " ");
while (token != NULL)
{
void *pointer;
size_t length;
pointer = realloc(instance.tokens, (1 + instance.count) * sizeof(char *));
if (pointer == NULL)
{
size_t i;
for (i = 0 ; i < instance.count ; ++i)
free(instance.tokens[i]);
free(instance.tokens);
instance.tokens = NULL;
instance.count = 0;
return instance;
}
instance.tokens = pointer;
length = strlen(token);
instance.tokens[instance.count] = malloc(1 + length);
if (instance.tokens[instance.count] != NULL)
strcpy(instance.tokens[instance.count], token);
instance.count += 1;
token = strtok(NULL, " ");
}
return instance;
}
int
main(int argc, char **argv)
{
room certainRoom;
size_t i;
if (argc < 1) /* invalid number of arguments */
return -1;
certainRoom = tokenizeString(argv[1]);
for (i = 0 ; i < certainRoom.count ; ++i)
{
printf("%s\n", certainRoom.tokens[i]);
/* we are done working with this token, release it */
free(certainRoom.tokens[i]);
}
/* all tokens where released, now released the main container,
* note, that this only contained the pointers, the data was
* in the space pointed to by these pointers. */
free(certainRoom.tokens);
return 0;
}