c - 将 char 数组中的指针分配给字符串 C 中的每个单词

标签 c arrays string pointers

我有一个最多 200 个字符的字符数组。我想为数组中的每个单词分配一个点数组。我有这张照片作为应该发生的事情的例子。 I am not allowed to post images so here is a link to the picture on imgur

我尝试遍历字符串以寻找空格,并为每次出现的地方分配一个新指针。但随后它每次都会打印剩余的字符串,然后崩溃。

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char str[200];
    char *arr[200];
    fgets(str, 200, stdin);
    arr[1] = &str[5];
    printf("%s", arr[1]);
    int i = 0;
    int next = 0;
    char ch = ' ';
    for (; i < 200; i++) {
        ch = str[i];
        if (ch == ' '){
            arr[next] = &str[i];
            next++;
        }
    }
    i = 0;
    for (; i < 200; i++) {
        printf("%s", arr[i]);
    }
    return 0;
}

最佳答案

修复样本。

#include <stdio.h>

int main() {
    char str[200];
    char *arr[sizeof(str)/2];//Enough if half
    fgets(str, sizeof(str), stdin);
    int i, j;
    char ch = ' ';
    for (j = i = 0; str[i] && str[i] != '\n'; i++) {//i < 200 is over run.
        if(ch == ' ' && str[i] != ' ')
            arr[j++] = &str[i];
        ch = str[i];
    }
    for (i = 0; i < j; i++) {//i < 200 is over run.
        printf("%s", arr[i]);
    }
    return 0;
}

#include <stdio.h>
#include <string.h>

int main() {
    char str[200];
    char *arr[sizeof(str)/2];
    fgets(str, sizeof(str), stdin);
    int i, j=0;
    char *word = strtok(str, " \t\n");
    while(word){
        arr[j++] = word;
        word = strtok(NULL, " \t\n");
    }
    for (i = 0; i < j; i++) {
        printf("%s\n", arr[i]);
    }
    return 0;
}

关于c - 将 char 数组中的指针分配给字符串 C 中的每个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26048845/

相关文章:

c - C 中带符号的单字节字符的 -(-128) 是什么?

javascript - 使用 JavaScript 中的 bool 属性对复杂的对象数组进行排序

c++ - 在分配字符串时分配右值引用

c++ - s[i]^=32 是如何将大写转换为小写的?

c - 删除链表中间的节点

c - 如何用C语言编写加密函数

c - CUDA 大整数加法

javascript - 在 Node.js 中弹出部分数组

android - 如何使用 JSON Web 服务填充 Android 微调器?

c# - 在 C# 中替换字符串