Home > Mobile >  How to count how many elements have been added to an array in C
How to count how many elements have been added to an array in C

Time:03-27

So basically I have an array with a size of 5 and I want to count how many elements it has inside it.

int main()
{
  int size;
  char ola[5];
  ola[0] = 'p'; 
  size = sizeof(ola); 
  printf("%d\n", size);
  return 0;
}

This code returns 5, but I expected 1. What should I change?

CodePudding user response:

The C standard does not provide any usable concept of elements in an array being used or unused. An array is simply a sequence of elements. It is up to you to track how many elements in it are of interest to you; you must write your own code for this.

You can do this by keeping a separate counter, by using a particular element value to denote that an element is “unused,” by using a particular element value to denote that an element ends the elements of interest, by calculating the end from related information, or by other means.

The C library includes many routines that use the third method, where the “null character,” with value zero, is used to mark the end of a string of characters. When you use this method, be sure to include room for the terminating null character in any array. For example, if you want an array to hold strings of length up to n characters, define the array to have at least n 1 elements.

CodePudding user response:

Keep a count as you add elements to the array, rather than using sizeof (which returns the total capacity of the array in bytes), for example

#include <stdio.h>

int main(void)
{
    int size = 0; // initialize size
    char ola[5] = ""; // also initialize ola (with 5 '\0's)
    ola[size  ] = 'p'; // use and increment size
    // size = sizeof(ola); // size is already updated
    printf("%d\n", size);

    // one more character
    ola[size  ] = 'o';
    printf("%d\n", size);

    printf("The string is [%s]\n", ola);

    return 0;
}

CodePudding user response:

It returns 5 because it is the size of your array, you could try:

  size = sizeof(ola[0]); 

To get the response 1, this mean that you are getteing exatly the size of the element, and not the size of whole array.

  •  Tags:  
  • c
  • Related