首页 > 解决方案 > 在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。如果我用它工作的单词数替换它正好。

标签: csplitmallocsizeof

解决方案


推荐阅读