c - 在c中获取字符串数组的维度的问题
问题描述
我创建了一个拆分字符串函数,并且得到了所需的输出。然而,在验证后,main
我似乎无法确定我的第一个维度的大小来遍历其中的每个单词。
这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char **split(char *str) {
int str_length = 0;
int i = 0;
int separator_count = 0;
while (str[i] != '\0') {
if (str[i] == ' ') {
separator_count++;
}
i++;
}
char **word_array;
word_array = malloc((separator_count + 2) * sizeof(char *));
int word_len = 0;
int separator_index = 0;
int b = 0; //to iterate over "str"
for (int a = 0; a < (separator_count + 2); a++) {
word_len = 0;
while (str_length < strlen(str) + 1) {
str_length++;
if (str[b] == ' ' || str[b] == '\0') {
separator_index = b;
word_array[a] = malloc(word_len * sizeof(char));
int word_depth = 0;
for (int c = (separator_index - word_len); c < separator_index; c++) {
chrctr = str[c];
word_array[a][word_depth] = str[c];
word_depth++;
}
word_array[a][word_len] = '\0'; //terminate found and stored word with null charachter
word_len = 0; //reset word length counter to 0
b++; //skip to next charachter
break; // break to go to next index of word_array
}
word_len++;
b++;
}
}
word_array[separator_count + 2] = NULL;
return word_array;
}
int main() {
char s[] = "A complete toolkit for building search into your product."; //test string
char **ss = split(s);
for (int i = 0; i < sizeof(ss); i++) { //here is the problem, and doing sizeof(ss)/sizeof(ss[0])=1 !!
for (int j = 0; j < strlen (ss[i]); j++) {
printf("%c", ss[i][j]);
}
printf ("\n");
}
}
我想验证我的输出 bat 似乎无法获得我看到的sizeof(array)/sizeof(array[0])
有效字符串数组的第一个维度的大小,它不适合我它产生 1。如果我用它工作的单词数替换它正好。
解决方案
推荐阅读
- wordpress - 使用 HAProxy 将 URL 重定向到 wordpress 服务器
- javascript - Vue.js (Nuxt) 返回 JSON 数据
- python - 为什么 cv2 read() 方法从网络摄像头提供裁剪图像?
- c# - 限制 BehaviorSubject 的值
- c# - 如何将多个参数从一个线程传递到下一个线程?
- php - 请问如何使用pdo将包含138个数组(如下所示)的php数组发布到mysql?
- python - 如何从用户传递多个值并在字典中搜索它们以返回键
- flutter - Firebase 未检测到登录用户
- python - 使用正则表达式解析日志
- php - 从不同子目录中的多个 .html/.php 文件引用的头文件中引用图像文件的正确方法是什么?