0

I am trying to find length of pointer array. Here is my code:

char **histargv[histsize];
histargv[hist] = (char**)malloc(sizeof(char *)*arg);

variable arg is not constant. Each index of histargv array has different arg value. So how can I find arg value for each index?

Thanks

  • 3
    Possible duplicate of [How to find the 'sizeof'(a pointer pointing to an array)?](http://stackoverflow.com/questions/492384/how-to-find-the-sizeofa-pointer-pointing-to-an-array) – Eli Sadoff Nov 27 '16 at 05:31
  • 2
    You can't find the length of a dynamically-allocated array just from its pointer. – qxz Nov 27 '16 at 05:32

1 Answers1

0

If the pointers are for strings, then you can figure out the length of the strings (not the size of the memory block) by using strlen. I.e. with:

for (size_t i = 0; i < 100; ++i) {
    histargv[i] = read_some_string_somehow_and_return_in_new_buffer();
}

you can print the string including their lengths like this:

for (size_t i = 0; i < 100; ++i) {
    printf("%3zu %zu %s\n", i, strlen(histargv[i]), histargv[i]);
}

If this are not strings, then you should follow the link in Eli Sadoffs comment.

Bodo Thiesen
  • 2,476
  • 18
  • 32
  • You can also find the length of the string without `strlen`. You can also do `int i;` and `for (i = 0; *(c+i) != '\0'; i++);` and then `i` will be the length of the string (assuming it's null terminated and `char * c` is the string). – Eli Sadoff Nov 27 '16 at 15:07
  • There are many ways, yes. But `strlen` is possibly much faster, because it can use system dependent optimisations, that your loop may not use. Also you can write `c[i]` instead of `*(c+i)`, you can drop `!= '\0'` completely, you can use `size_t` as data type for `i` instead of `int` and and and ;) – Bodo Thiesen Nov 27 '16 at 20:04