-5

My goal is to print all elements of an array of integers regardless of its length. I would like to print it in Python list format, but then I got this error. Here is my code

int measure(int n[])
{
    int num=0;
    while (n[num]) { num++; }
    return num;
}

void show(int n[])
{
    int a = measure(n);
    for (int i=0; i<a; i++) {
        if (i==0) { printf("[%d,",n[i]); }
        else if (i==a-1) { printf(" %d]",n[i]); }
        else { printf(" %d,",n[i]); }
    }
}

int main(void)
{
    int arr[10] = {1,2,3,4,5,6,7,8,9,10};
    show(arr);
    
}

It is supposed to print this: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] but I got this instead: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1935094528, -1664206169]

then I replace show() with this:

int i=0;
    while (n[i]) {
        if (i==0) { printf("[%d,",n[i]); i++; }
        else if (n[i+1] == NULL) { printf(" %d]",n[i]); break; }
        else { printf(" %d,",n[i]); i++; }
    }

and then I got these:

main.cpp:23:28: warning: NULL used in arithmetic [-Wpointer-arith]
   23 |         else if (n[i+1] == NULL) { printf(" %d]",n[i]); break; }
      |                            ^~~~
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, -680101376, -1228044632]

Why does this happen?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
seggsyape
  • 15
  • 3
  • 1
    Your code has nothing common with C++. – Vlad from Moscow Feb 07 '22 at 16:33
  • 1
    What makes you believe, that arrays always are appended a zero value? – πάντα ῥεῖ Feb 07 '22 at 16:34
  • If the sizing operation worked, your code would print `[1,]` for a 1-element array. You need to reconsider your printing algorithm. Probably print `[` before any other output; then print the numbers separated by comma-space; then print `]` after everything else. There are various ways to organize the separator; generally, I prefer `const char *pad = ""; before the loop; `printf("%s%d", pad, number); pad = ", ";` in the loop. – Jonathan Leffler Feb 07 '22 at 16:40
  • I suspect that you don't know what `while (n[num])` does. Your code seems to assume that `n[num]` will evaluate to `false` if `num` is not a valid index for `n`. `n[num]` is actually Undefined Behavior if `num` is not a valid index. – Drew Dormann Feb 07 '22 at 16:40
  • 1
    On the warning: `NULL` is a pointer, and pointers are not the same as an `int`. A great many bugs have resulted from people using pointers as `int`s and vice-versa, so C++ warns you that you're probably waling into a boobytrap. – user4581301 Feb 07 '22 at 16:42
  • You can just pass it to function `show` when you call it: `show(arr, sizeof(arr) / sizeof(*arr))`. And from there, you can pass it on to function `measure` when you call it. –  Feb 07 '22 at 16:42
  • You can just pass it to function `show` when you call it: ``` void show(int n[], size_t len) { printf("[%d,", n[i]); for (size_t i = 1; i < len - 1; i++) printf(" %d,", n[i]); printf(" %d]", n[i]); } int main(void) { int arr[] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}; show(arr, sizeof(arr) / sizeof(*arr)); return 0; } ``` –  Feb 07 '22 at 16:50
  • I have a suspicion this is an attempt of writing C++ using Python as a model in writing the code. If so, do not use other programming languages as models in writing C++ code. You'll only introduce bugs, write inefficient code, or write code that looks weird to a C++ programmer. And worse, if you don't know C++ and try to work your way through writing a C++ program by using Python as a "guide", you will waste time making mistakes that you're making now. For example, arrays decay to pointers when passed to functions, but you will never know this by using Python to guide you. – PaulMcKenzie Feb 07 '22 at 16:55
  • 1
    This looks more like C code than C++ code. Use `std::array` (with the functions as template functions) or `std::vector` to begin with. – Sebastian Feb 07 '22 at 17:15

2 Answers2

2

How do I measure the length of an int array in C++?

You can use std::size to get the size of an array with known size:

int arr[10] = {1,2,3,4,5,6,7,8,9,10};
std::cout << std::size(arr);

Why does this happen?

Because the continue condition for your loop is "while the element is not 0". There are no elements with the value 0, so the loop doesn't end before exceeding the end of the array, at which point your overflow the array and the behaviour of the program becomes undefined.

The parameter n of the functions measure and show is not an array of known size. Since n isn't an array of known size, you cannot use std::size to get its size. In fact, although it looks like an array of unspecified size, n is adjusted to be a pointer to element of such array. There is no general way to measure the size of an array given a pointer to its element.

In cases where you want to pass array of any size into a function, and also need to know the size of the array within the function, a good solution is to use a span parameter:

void show(std::span<int> n)
eerorika
  • 232,697
  • 12
  • 197
  • 326
  • Does that work in a function where the definition of the array is not visible? – Jonathan Leffler Feb 07 '22 at 16:41
  • And if your tools have yet to reach C++17 where `std::size` was added, writing your own's [not that hard](https://en.cppreference.com/w/cpp/iterator/size#Possible_implementation) – user4581301 Feb 07 '22 at 16:41
  • @JonathanLeffler Yes, but if the variable isn't in scope, then you must use indirection. – eerorika Feb 07 '22 at 16:58
0

There simply is no "measuring" the length of arrays in C++. You have to know up front, and pass that info to any functions or methods you pass the array to. You can also use a specific "tag" value (as you have implicitly done here) but if you do that, you have to set the tag yourself, and that means you have to know the array length to set the tag. And you must be very sure that the tag does not equal any valid data value in your array.

A different approach would be to use std::vector instead of an array. That data type gives you all the functionality of an array but also provides variable length arrays and the ability to inquire the current length.

Logicrat
  • 4,438
  • 16
  • 22
  • Supplementary reading: [What is array to pointer decay?](https://stackoverflow.com/questions/1461432/what-is-array-to-pointer-decay) – user4581301 Feb 07 '22 at 16:44