简体   繁体   English

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

[英]Assign a pointer in a char array to each word in a string C

I have a array of chars that is a maximum of 200 characters. 我有一个最多200个字符的字符数组。 I would like to assign an array of points to each word in the array. 我想为数组中的每个单词分配一个点数组。 I have this picture as an example of what is supposed to happen. 我有这张照片作为应该发生的事的一个例子。 I am not allowed to post images so here is a link to the picture on imgur 我不允许发布图片,因此这是指向imgur图片的链接

I have tried looping over the string looking for white spaces, assigning a new pointer to each occurrence. 我尝试遍历字符串以寻找空白,并为每次出现分配新的指针。 But then it prints the remaining string each time and then crashes. 但是,它每次都会打印剩余的字符串,然后崩溃。

#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;
}

如果内容中的空白少于200个,则输出循环将从arr [i]抓取一个指向随机地址的指针,并将其提供给printf ...这可能会导致崩溃。

sample to fix. 修复样品。

#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;
}

You have two options: 您有两种选择:

1) if the string is modifyable you can change the first whitespace character after each word to '\\0'. 1)如果字符串是可修改的,则可以将每个单词后的第一个空格字符更改为'\\ 0'。 This will let you print using the pointers you store, but the original string won't print properly anymore. 这将使您可以使用存储的指针进行打印,但是原始字符串将不再正确打印。

2) store the length of the string and the pointer in a struct, and have a custom function the can print them for you. 2)将字符串和指针的长度存储在结构中,并具有一个自定义函数,可以为您打印它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM