c - 如何使用指向切片字符串的指针的指针

标签 c string function pointers memory-management

我在 tutorialsPoint 上读到了关于指针的指针.

我自己做了一个小测试。我想按空格对字符串进行切片,以便将每个单词(包括标点符号)视为一个标记,并逐行返回标记。

这是代码:

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

char** split(const char* s)
{
    int i = 0, j = 0;
    char** word = malloc(strlen(s)+1);
    * word = malloc(strlen(s)+1);

    while (*s != '\0') {
        if (*s == ' ') {
            i++;
        } else {
            word[i][j] = *s;
            j++;
        }
        i++;
        s++;
    }

    return word;
    //free(word);  //with or without this i get the same outcome.
}

int main(void)
{
    char** words = split("He said 'hello' to me!");
    int i = 0;
    while (words[i] != NULL) {
        puts(words[i]);
        free(words[i]);
        i += 1;
    }
    free(words);
}

它可以编译,但是当我在终端上运行时,出现段错误。我在 if 语句中添加了一个 printf ,它会打印每个字母。

我也使用了valgrind,但我无法理解它在说什么。

预期输出:

He
said
'hello'
to
me!

最佳答案

split像这样修复。

char **split(const char *s){
    int i = 0, j;
    int len = strlen(s);
    len += (len & 1);//+1 if len is odd
    char **word = malloc((len / 2 + 1) * sizeof(*word));//+1 for NULL

    while (*s) {
        while(*s == ' ')
            ++s;//skip spaces
        if(!*s)
            break;
        for(len = 0; s[len] && s[len] != ' '; ++len)
            ;
        word[i] = malloc(len + 1);
        for(j = 0; j < len; ++j)
            word[i][j] = *s++;
        word[i++][j] = '\0';
    }
    word[i] = NULL;
    return word;
}

关于c - 如何使用指向切片字符串的指针的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39283818/

相关文章:

c - 添加另一个循环后执行停止(C,Project Hangman)

c++ - 这段代码有什么问题?

java - new string(byte[]) 在多线程应用程序中太慢

python - 为什么我的程序没有显示我告诉它的碰撞框?

c - 调试 postgresql for where 'A' < 'a'

c - 如何用 C 读取 CSV 文件的第一个条目?

c - 在 C 中只将一个参数传递给 main()

java - 将字符串转换为以 0 开头的整数

c++ - 使用在当前函数下面声明的函数(允许循环依赖)?

php - fatal error : Call to a member function error() on a non-object