我在 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/