Как найти размер массива char

You can’t. Not with 100% accuracy, anyway. The pointer has no length/size but its own. All it does is point to a particular place in memory that holds a char. If that char is part of a string, then you can use strlen to determine what chars follow the one currently being pointed to, but that doesn’t mean the array in your case is that big.
Basically:

A pointer is not an array, so it doesn’t need to know what the size of the array is. A pointer can point to a single value, so a pointer can exist without there even being an array. It doesn’t even care where the memory it points to is situated (Read only, heap or stack… doesn’t matter). A pointer doesn’t have a length other than itself. A pointer just is…
Consider this:

char beep = 'a';
void alert_user(const char *msg, char *signal); //for some reason
alert_user("Hear my super-awsome noise!", &beep); //passing pointer to single char!

void alert_user(const char *msg, char *signal)
{
    printf("%s%cn", msg, *signal);
}

A pointer can be a single char, as well as the beginning, end or middle of an array…
Think of chars as structs. You sometimes allocate a single struct on the heap. That, too, creates a pointer without an array.

Using only a pointer, to determine how big an array it is pointing to is impossible. The closest you can get to it is using calloc and counting the number of consecutive chars you can find through the pointer. Of course, that doesn’t work once you’ve assigned/reassigned stuff to that array’s keys and it also fails if the memory just outside of the array happens to hold , too. So using this method is unreliable, dangerous and just generally silly. Don’t. Do. It.

Another analogy:
Think of a pointer as a road sign, it points to Town X. The sign doesn’t know what that town looks like, and it doesn’t know or care (or can care) who lives there. It’s job is to tell you where to find Town X. It can only tell you how far that town is, but not how big it is. That information is deemed irrelevant for road-signs. That’s something that you can only find out by looking at the town itself, not at the road-signs that are pointing you in its direction

So, using a pointer the only thing you can do is:

char a_str[] = "hello";//{h,e,l,l,o,}
char *arr_ptr = &a_str[0];
printf("Get length of string -> %dn", strlen(arr_ptr));

But this, of course, only works if the array/string is -terminated.

As an aside:

int length = sizeof(a)/sizeof(char);//sizeof char is guaranteed 1, so sizeof(a) is enough

is actually assigning size_t (the return type of sizeof) to an int, best write:

size_t length = sizeof(a)/sizeof(*a);//best use ptr's type -> good habit

Since size_t is an unsigned type, if sizeof returns bigger values, the value of length might be something you didn’t expect…

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:

  1. Pass along a length paramenter too. (Think int main(int argc, char
    *argv
    )).
  2. Design your array so every element is non-NULL, except the last
    element. (Think char *s="almost a string"; or execve(2).)
  3. Design your function so it takes some other descriptor of the
    arguments. (Think printf("%s%i", "hello", 10); — the string describes
    the other arguments. printf(3) uses stdarg(3) argument handling, but
    it could just as easily be an array.)

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.

  1. Use the sizeof Operator to Find Length of Char Array
  2. Use the strlen Function to Find Length of Char Array

Get Length of Char Array in C

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

Improve Article

Save Article

Like Article

  • Read
  • Discuss
  • 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

    Понравилась статья? Поделить с друзьями:
  • Как исправить защитное стекло на телефоне попал воздух
  • Как в ноуте найти действие крышки
  • Как найти ленту вкладок
  • Формула по физике как найти работа
  • Математика как найти ноз