如何获得char **的大小?

时间:2016-03-01 10:10:11

标签: c

我想计算我的数组的大小(有多少值/索引)。 我在StackOverflow上找到了类似的东西

char **sentences;

while ((c = fgetc(fp)) != EOF) { 
    ... fill the array...
}

size_t w = sizeof(sentences); // this is wrong! it returns size of pointer (memory)

它给了我“w = 4”但我的数组有6条记录。 我需要这个用于“for循环”来打印我的结果(尝试计算“while”中的每个循环,但我在不同的函数中得到它,我不知道在数组中返回2个值[count | array of strings])

我很高兴知道如何打印整个阵列。

1 个答案:

答案 0 :(得分:1)

您可以像这样返回实际的数量:

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

char **doSomething(size_t *count) {
  char **sentences;
  // Mock initialization of sentences, please skip :-)
  sentences = (char **)calloc(13, sizeof(char *));
  for (int i = 0; i < 13; i++) {
    sentences[i] = (char *)calloc(8, sizeof(char));
    sprintf(sentences[i], "quux-%d", i); // Just filling in some foobar here.
  }
  // ---------

  *count = 13; // <-- Look here, we're dereferencing the pointer first.
  return sentences;
}

int main(int argc, char **argv) {
  size_t size;
  char **res;

  // Sending the address of size, so the function can write there.
  res = doSomething(&size);

  for(size_t i = 0; i < size; i++)
    printf("res[%lu]: %s\n", i, res[i]); // You should see the filler outputted to stdout.

  return 0;
}