2

I know it's possible to use the sizeof function to get the size, but it doesn't get a true count of the array length. If I set an array of int 50 and I stored only 10 numbers in there, I would want to get 10 as the number of elements, but of course that won't happen. I know this is definitely a trivial question, but bear with me here and help me on this if it is possible.

My code so far takes an entire sentence and stores it in an array.

#include <stdio.h>
#include <string.h>

int main()
{
    int i=0;
    char array[50]={0};
    fgets(array, 50, stdin);
    int len = sizeof(array);  // it doesn't work :((((((
    for(i=0; i<len; i++)
    {
        printf("%c\n", array[i]);
    }
    return 0;

}

As you guys can see, if the user decides to only enter a word of lets say "Bobby Foo" then I would want len number of 9 including the space, but the sizeof function only gets length of the size of the array declared which is 50.. >.>..

Jongware
  • 22,200
  • 8
  • 54
  • 100
Belphegor
  • 1,683
  • 4
  • 23
  • 44
  • Sadly, C arrays are just low level blobs of memory. Its the responsibility of the programmer to keep track (using a separate variable) of how many elements are stored in the array and in what positions of the array they are stored in. – hugomg Oct 05 '14 at 04:17
  • How about a function that searches the array for the newline character? – Beta Oct 05 '14 at 04:17
  • 1
    You may find this question informative: [**"sizeof-vs-strlen"**](http://stackoverflow.com/questions/9937181/sizeof-vs-strlen) – WhozCraig Oct 05 '14 at 04:19
  • The only way I know how to go through an array(search) is with a for loop, and that would mean I need to know what n (length is). I know there's other ways, but I am still a noob at this. – Belphegor Oct 05 '14 at 04:20
  • 1
    possible duplicate of [How do I determine the size of my array in C?](http://stackoverflow.com/questions/37538/how-do-i-determine-the-size-of-my-array-in-c) – iqstatic Oct 05 '14 at 04:20
  • Strictly, the size of your array is 50, because arrays do not have 'not-set' value -- any bit pattern is valid. – user3125367 Oct 05 '14 at 05:06

2 Answers2

2

Q: Is it possible to get the number of elements currently stored in an array in C?

  1. Short answer: No. You need to track this information yourself.

  2. You happen to be using fgets() with a character array. Since in this case you're getting a C "string", you can use the C function strlen().

  3. It's worth noting that fgets() will also return a newline - so your string might be a one (Mac, Linux) or two (DOS/Windows) characters longer than you expect.

PS:

Here is a bit more about C strings, including the concept of "null termination" (if you're not already familiar with them):

http://www.cprogramming.com/tutorial/c/lesson9.html

Jabberwocky
  • 48,281
  • 17
  • 65
  • 115
FoggyDay
  • 11,962
  • 4
  • 34
  • 48
  • yes you are correct, it does have a newline and when I printf it gives me these 2 blank spaces. I am assuming I can just delete this new line later on. – Belphegor Oct 05 '14 at 04:21
  • 1
    Ad 3) `fgets` is most often used to read from _text streams_ (like `stdin`), so new-line (whatever it happens to be on some system) is converted to `'\n'`. – mafso Oct 05 '14 at 04:46
0

Use strlen to get the size of the array. You need to include string.h.

sizeof() is not a function it is an operator. When sizeof is applied to the name of a static array (not allocated through malloc), the result is the size in bytes of the whole array.

If you are using fgets, then you need to remove \n from the string. A simple way would be:

array[strlen(array) - 1] = '\0';

A quick example:

#include <stdio.h>
#include <string.h>
#include <stddef.h>

int main()
{
    int i=0;
    char array[50]={0};
    char *p;
    fgets(array, 50, stdin);
    //Remove `\n` from the array.
    if ((p=strchr(array, '\n')) != NULL)
        *p = '\0';
    size_t len = strlen(array);  // Use strlen to find the length of string
    for(i=0; i<len; i++)
    {
        printf("%c\n", array[i]);
    }
    return 0;
}
ani627
  • 5,578
  • 8
  • 39
  • 45
  • Wait are you serious :D? I was under the assumption we needed some sort of actual code algorithm. So this would ONLY count the number of elements stored inside including the space? – Belphegor Oct 05 '14 at 04:16
  • @user3718584 `strlen()` will count the number of `char`s in the array up until the first non-NULL character. – Code-Apprentice Oct 05 '14 at 04:17
  • @user3718584 As long as the char array is NUL terminated – Novaterata Oct 05 '14 at 04:18
  • I am not sure what you mean by NUL terminated, but it does always end in a newline as well when I press enter. I would assume the newline char would also be counted. – Belphegor Oct 05 '14 at 04:19
  • Yup, I just did that after finding out from you guys that I have to use a '\0' to get rid of the newline, before I was going to set it to 0 lol.. – Belphegor Oct 05 '14 at 04:30
  • 2
    Probably should check for '\n' before removing it and not use strlen twice. – user3125367 Oct 05 '14 at 05:01
  • 1
    `strlen(array) - 1` mostly is way into desaster. Using the `strchr()` approach is the way to go. Also note that `fgets()` does not append the `\n` in any case. @user3718584 – alk Oct 05 '14 at 08:10
  • 1
    `strlen()` returns `size_t` not `int`, same for `sizeof`. – alk Oct 05 '14 at 08:11
  • @alk: Thanks, by reading your suggestion I read more about `size_t`. Could you please explain why `strlen(array) - 1` is disaster? Also I'm unclear regarding your statement that _`fgets()` does not append the `\n` in any case_. Reason why I'm asking is when we accept input using `fgets()`, I see `\n` in the end. – ani627 Oct 06 '14 at 10:19
  • 1
    @1336087: 1.: `strlen(array) - 1`: Imagine what would happen if you'd pass in `""` to `strlen() - 1`? 2.: If `fgets()` encounters `EOF` before a `\n`, it would not append a `\n`. – alk Oct 06 '14 at 10:26