Error in determining the number of elements of an array in C++


// TestLesson.cpp: определяет точку входа для консольного приложения.

#include "stdafx.h"
#include <iostream> 
#include <cstdlib>  
using namespace std; 

int main()
    setlocale(LC_ALL, "rus");
    int* size = new int;
    cin >> *size;
    cout << "Элементы массива: | ";
    char* arrayChar = new char[*size];
    for (int k = 0; k < *size; k++) {
        arrayChar[k] = 'a' + k;
        cout << arrayChar[k] << " | ";
    cout << endl;
    cout << strlen(arrayChar);
    return 0;

Why does the srtlen() method output more answers than actually given ones (specified at the time of declaration)? And at what it does not matter which array: static or dynamic. I am using Microsoft Visual Studio 2017


The strlen function is designed to determine the length of C-strings. The argument to the strlen function can only be a pointer to the beginning of a C-string. Otherwise, the behavior is undefined.

A C-string is a sequence of characters of type char ending in '\0' . Do you have these requirements in your code? No. Therefore, using the strlen function in your code causes undefined behavior . What are you observing.

The strlen function has nothing to do with the "determining the number of array elements" mentioned in the title of your question. Moreover, there is no built-in means in C++ to determine the number of elements of an array allocated via new [] .

In your code, you already know the size of your array – it's *size . Take good care of this size and use it wherever you need it. Of course, instead of a "bare" array, you can use std::vector , which will store this size for you.

Scroll to Top