分解字符串并将其存储在数组中
我想分解一个句子并将每个字符串存储在一个数组中。这是我的代码:
#include <stdio.h>
#include <string.h>
int main(void)
{
int i = 0;
char* strArray[40];
char* writablestring= "The C Programming Language";
char *token = strtok(writablestring, " ");
while(token != NULL)
{
strcpy(strArray[i], token);
printf("[%s]\n", token);
token = strtok(NULL, " ");
i++;
}
return 0;
}
它一直给我分段错误,我无法弄清楚。我相信当我将令牌复制到我的数组时它会发生一些事情。
I want to break down a sentence and store each string in an array. Here is my code:
#include <stdio.h>
#include <string.h>
int main(void)
{
int i = 0;
char* strArray[40];
char* writablestring= "The C Programming Language";
char *token = strtok(writablestring, " ");
while(token != NULL)
{
strcpy(strArray[i], token);
printf("[%s]\n", token);
token = strtok(NULL, " ");
i++;
}
return 0;
}
It keeps giving me segmentation error and I cannot figure it out. I believe it has something to do when I copy the token to my array.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
这是因为
writablestring
根本不可写。尝试写入字符串文字是未定义的行为,strtok
会写入它(没错,strtok
会修改其参数)。要使其正常工作,请尝试:
还有一个 C 常见问题解答。
另一个问题是您没有为字符指针数组分配内存(因此这些指针指向任何内容)。
也许试试这个?
It's because
writablestring
isn't writable at all. Attempting to write to a string literal is undefined behavior andstrtok
writes to it (that's right,strtok
modifies its argument).To make it work, try:
There's also a C FAQ.
Another problem is that you didn't allocate memory for your array of character pointers (so those pointers point to nothing).
Maybe try this ?
看看文档中的示例:
...其中.. 。
您需要我可以修改第一个字符串,并且需要为输出分配内存,例如
Have a look at the example in the docs:
...where...
You need that first string to me modifiable and you need to allocate memory for the outputs e.g.