打破字符串,并将其存储在阵列 [英] Breaking down string and storing it in array

查看:131
本文介绍了打破字符串,并将其存储在阵列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想打破一个句子,并存储在数组中的每个字符串。这里是我的code:

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.

推荐答案

这是因为 writablestring 不可写的。试图写入字符串是未定义的行为和 strtok的写入到它(没错, strtok的修改其参数)。

It's because writablestring isn't writable at all. Attempting to write to a string literal is undefined behavior and strtok writes to it (that's right, strtok modifies its argument).

要使它发挥作用,请尝试:

To make it work, try:

char writablestring[] = "The C Programming Language";

还有一个Ç常见问题解答

另一个问题是,你没有为你的字符指针(所以这些指针指向没有)数组分配内存。

Another problem is that you didn't allocate memory for your array of character pointers (so those pointers point to nothing).

char* strArray[40]; /* Array of 40 char pointers, pointing to nothing. */

也许试试这个?

/* Careful, strdup is nonstandard. */
strArray[i] = strdup(token);

/* Or this. */
strArray[i] = malloc(strlen(token) + 1);
strcpy(strArray[i], token);

这篇关于打破字符串,并将其存储在阵列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆