Well, 11 years later, I run into this issue with a college assignment. The solution I found, worked without having to alter the function signatures that the assignment was asking for.
In my case, I had to make a function that returns the item index if the item existed or depending on if the itemPrefix (e.g. ‘B’ for Banana) already exists or not in the character array itemPrefixes to avoid passing duplicate prefixes.
So, I had to use a for
loop (or while
loop). The problem was that the assignment had given me specific signatures for each function and for that specific function it didn’t allow me to pass the count
variable that was on the main()
function as an argument.
I had to improvise.
Both the ways mentioned above didn’t work. strlen()
didn’t work as intended since there was not a ''
end character that strings have. The sizeof()
method also didn’t work, because it returned the size of the pointer of the character array that was passed in as an argument instead of the number of elements.
So, this is the function I came up with. A simple while loop that checks whether the current character is NULL
(or 0
).
void charArrLength(char array[]) {
int arrLength = 0;
while (array[arrLength] != 0) {
arrLength++; //increment by 1
}
printf("Character array has %d elements", arrLength);
}
For this to work though, in the main()
function, you need to declare your character array as a character pointer and then allocate the memory that you need based on the number of items that you ultimately wish to have inside your array.
void charArrLength(char array[]) {
int arrLength = 0;
while (array[arrLength] != 0) {
arrLength++;
}
printf("Character array has %d elements", arrLength); //should give 33
}
int main() {
char *array; //declare array as a pointer
int arraySize = 33; //can be anything
array = (char*) malloc(arraySize * sizeof(char));
charArrLength(array);
free(array); //free the previously allocated memory
}
Below you will see how I utilised this function in my assignment.
First, here is the above function tailored to my needs.
int isItemExists(char itemPrefixes[], char itemPrefix) {
int count = 0; //declare count variable and set to 0
int itemIndex = -1; //declare item index variable and set it to -1 as default
while (itemPrefixes[count] != 0) {
count++;
}
for (int i = 0; i < count; i++) {
if (itemPrefix == itemPrefixes[i]) {
itemIndex = i; //if item exists, set item index to i
}
}
return itemIndex;
}
Then, how I declared the itemPrefixes
array in main()
function and how I allocated the needed memory based on n
(the number of items the user would like to add to itemPrefixes
array).
char *itemPrefixes;
int n = 0; //number of items to be added variable
printf("> Enter how many items to add: ");
scanf("%d", &n);
//allocate n * size of char data type bytes of memory
itemPrefixes = (char*) malloc(n * sizeof(char));
And finally, here is how that function was used after all.
do {
printf("nn> Enter prefix for item %d: ", i + 1);
scanf(" %c", &itemPrefix);
//prompt the user if that itemPrefix already exists
if (isItemExists(itemPrefixes, itemPrefix) != -1) {
printf("nItem prefix already exists! Try another one.n");
}
} while (isItemExists(itemPrefixes, itemPrefix) != -1);
Also, in the end of the code I free the previously allocated memory.
free(itemPrefixes);
To clear this out, again, this could be much easier if the conditions were different. The assignment was strict about not passing n
as an argument. Nevertheless, I hope I help someone else that might be looking for this in the future!
Just for the sake of it, if anybody sees this and has something simpler to suggest, feel free to tell me.
C is doing some trickery behind your back.
void foo(int array[]) {
/* ... */
}
void bar(int *array) {
/* ... */
}
Both of these are identical:
6.3.2.1.3: Except when it is the operand of the sizeof operator or the unary & operator,
or is a string literal used to initialize an array, an expression that has type
‘‘array of type’’ is converted to an expression with type ‘‘pointer to type’’
that points to the initial element of the array object and is not an lvalue. If
the array object has register storage class, the behavior is undefined.
As a result, you don’t know, inside foo()
or bar()
, if you were
called with an array, a portion of an array, or a pointer to a single
integer:
int a[10];
int b[10];
int c;
foo(a);
foo(&b[1]);
foo(&c);
Some people like to write their functions like: void foo(int *array)
just to remind themselves that they weren’t really passed an array,
but rather a pointer to an integer and there may or may not be more
integers elsewhere nearby. Some people like to write their functions
like: void foo(int array[])
, to better remind themselves of what the
function expects to be passed to it.
Regardless of which way you like to do it, if you want to know how long
your array is, you’ve got a few options:
- Pass along a length paramenter too. (Think
int main(int argc, char
)).
*argv - Design your array so every element is non-
NULL
, except the last
element. (Thinkchar *s="almost a string";
orexecve(2)
.) - Design your function so it takes some other descriptor of the
arguments. (Thinkprintf("%s%i", "hello", 10);
— the string describes
the other arguments.printf(3)
usesstdarg(3)
argument handling, but
it could just as easily be an array.)
Improve Article
Save Article
Like Article
Improve Article
Save Article
Like Article
Given a char variable and a char array, the task is to write a program to find the size of this char variable and char array in C.
Examples:
Input: ch = 'G', arr[] = {'G', 'F', 'G'} Output: Size of char datatype is: 1 byte Size of char array is: 3 byte Input: ch = 'G', arr[] = {'G', 'F'} Output: Size of char datatype is: 1 byte Size of char array is: 2 byte
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
Approach:
In the below program, to find the size of the char variable and char array:
- first, the char variable is defined in charType and the char array in arr.
- Then, the size of the char variable is calculated using sizeof() operator.
- Then the size of the char array is find by dividing the size of the complete array by the size of the first variable.
Below is the C program to find the size of the char variable and char array:
#include <stdio.h>
int
main()
{
char
charType =
'G'
;
char
arr[] = {
'G'
,
'F'
,
'G'
};
printf
(
"Size of char datatype is: %ld byten"
,
sizeof
(charType));
size_t
size =
sizeof
(arr) /
sizeof
(arr[0]);
printf
(
"Size of char array is: %ld byte"
,
size);
return
0;
}
Output:
Size of char datatype is: 1 byte Size of char array is: 3 byte
Last Updated :
15 Oct, 2019
Like Article
Save Article
- Use the
sizeof
Operator to Find Length of Char Array - Use the
strlen
Function to Find Length of Char Array
This article will explain several methods of getting the length of a char
array in C.
Use the sizeof
Operator to Find Length of Char Array
Array size can be calculated using sizeof
operator regardless of the element data type. Although, when measuring the array’s size, there might be some hideous errors if the inner details are ignored.
Namely, the following example is initializing two arrays named arr
and arr2
with different notations. Then sizes of both arrays are retrieved using the sizeof
operator and printed to the console.
Note that the second array size is equal to 18 bytes even though there are only 17 printed elements. The cause of this issue is hiding in the method of initialization, namely when char
array is initialized using a string literal value, the terminating null byte is also stored as a part of the array. Thus the sizeof
operator includes this byte in the sum of all elements and returns the corresponding result.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
void printCharArray(char *arr, size_t len)
{
for (size_t i = 0; i < len; ++i) {
printf("%c, ", arr[i]);
}
printf("n");
}
int main(int argc, char *argv[]){
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
char arr2[] = "array initialized";
printCharArray(arr, sizeof arr);
printf("size = %lu bytes n", sizeof arr);
printf("n");
printCharArray(arr2, sizeof arr2-1);
printf("size = %lu bytes n", sizeof arr2);
exit(EXIT_SUCCESS);
}
Output:
a, b, c, d, e, f, g,
size = 7 bytes
size = 24 bytes
a, r, r, a, y, , i, n, i, t, i, a, l, i, z, e, d,
size = 18 bytes
size = 17 bytes
Use the strlen
Function to Find Length of Char Array
In some scenarios, char
arrays that were initialized or stored as the null-terminated character strings can be measured for size using the strlen
function, which is part of the C standard library string utilities.
If we run the previous example code with strlen
calculated values, we get different numbers caused by separate issues. The first — arr
object size is printed to be 24 bytes because the strlen
function iterates through a char array until the terminating null byte is encountered. Thus, calling strlen
on arr
object resulted in iterating over both arr
and arr2
, since the first array is not terminated with null byte and the compiler stored the arr2
continuously after it, resulting in a size equal to the sum of both arrays minus 1 (discarding the terminating null byte).
Note that, lengthOfArray
function implemented by us imitates the strlen
counting behavior and results in the same numbers. For the second array object — arr2
, strlen
returned the number of printed characters without the last null byte, which can be useful in some scenarios, but it does not represent the array’s actual size.
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
void printCharArray(char *arr, size_t len)
{
for (size_t i = 0; i < len; ++i) {
printf("%c, ", arr[i]);
}
printf("n");
}
long lengthOfArray(const char *arr)
{
long size = 0;
while (*arr) {
size += 1;
arr +=1;
}
return size;
}
int main(int argc, char *argv[]){
char arr[] = {'a', 'b', 'c', 'd', 'e', 'f', 'g'};
char arr2[] = "array initialized";
printCharArray(arr, sizeof arr);
printf("size = %lu bytes n", sizeof arr);
printf("size = %lu bytes n", strlen(arr));
printf("size = %lu bytes n", lengthOfArray(arr));
printf("n");
printCharArray(arr2, sizeof arr2-1);
printf("size = %lu bytes n", sizeof arr2);
printf("size = %lu bytes n", strlen(arr2));
printf("size = %lu bytes n", lengthOfArray(arr2));
exit(EXIT_SUCCESS);
}
Output:
a, b, c, d, e, f, g,
size = 7 bytes
size = 24 bytes
size = 24 bytes
a, r, r, a, y, , i, n, i, t, i, a, l, i, z, e, d,
size = 18 bytes
size = 17 bytes
size = 17 bytes
This tutorial will discuss about a unique way to get the length of char array in C++.
Get maximum number of elements an array can hold
We can get the length of a char array, just like an another array i.e. fetch the actual size of array using sizeof(arr)
, and divide it with the size of first element in array i.e. sizeof(arr[0])
. It will give us the size of array i.e. the number of maximum characters that this array can hold. For example,
char arr[10] = "sample"; // Get length of a char array size_t len = sizeof(arr) / sizeof(arr[0]); std::cout<< len << std::endl;
Output:
Advertisements
10
As the string in this char array contains only 5 characters. But as the char array can hold 10 characters, therefore it returned the value 10.
Get the number of characters in a char array (string)
We can use the strlen()
function from string.h
header file. It accepts a char array as an argument, and treats the value in char array as a null terminated string. It returns the number of character in string holded by the char array. It excludes the null character at the end of string.
Frequently Asked:
- Check if Char Array is empty in C++
- Convert Char Array to Double or Number in C++
- Check if Char Array Starts with a string in C++
- How to initialize a Char Array in C++?
char arr[10] = "sample"; // Get number of characters in a char array size_t count = strlen(arr); std::cout<< count << std::endl;
Output:
6
As there were only six characters in the string, therefore it returned the value 6.
Let’s see the complete example,
#include <iostream> #include <string.h> using namespace std; int main() { char arr[10] = "sample"; // Get length of a char array size_t len = sizeof(arr) / sizeof(arr[0]); std::cout<< len << std::endl; // Get number of characters in a char array size_t count = strlen(arr); std::cout<< count << std::endl; return 0; }
Output :
10 6
Summary
Today we learned about several ways to get the length of char array in C++. Thanks.