0

So I created a dynamically allocated array of structs pretend that structtype is the name of the struct, and arr is the array.

structtype * arr; arr = new structtype[counter+15]; 

Then I attempted to pass that array of structs into multiple types of functions with prototypes such as:

void read_info(structtype (&arr)[15], int integer); 

and

void Append(structtype arr[15]); 

In turn I got these errors:

error: cannot convert ‘structtype’ to ‘structtype (&)[15]’ 

and

error: cannot convert ‘structtype**’ to ‘structtype (&)[15]' 

Can yall help me figure out how to get rid of these errors, for example dereferencing the pointer part of the array or something.

2
  • 2
    You don't have an array, you have a pointer, because new give you a pointer. It can't give you an array, because an array's size must be known at compile time. You need to change your function signatures to take a pointer. But really, you should just use std::vector instead. Commented Aug 6, 2022 at 22:24
  • Don't, just don't. C-style arrays are really bad to work with. Use std::array or std::vector instead and use std::span if you want your function to be flexible in what it takes as argument. Commented Aug 8, 2022 at 10:14

1 Answer 1

2

Your array is somewhere in memory, location which is pointed by the actual variable arr the pointer.

The array is therefore represented by the pointer, however the pointer carries no information about where the array ends or its size, unlike std::vector<>.

So you need to pass it with the known size as in:

#include <cstdio> struct structtype { int a; }; void dosomething( structtype* s, int size ) { for ( int j=0; j<size; ++j ) { printf( "s[%d]=%d\n", j, s[j] ); } } int main() { int counter = 50; structtype * arr; arr = new structtype[counter+15]; dosomething( arr, counter + 15 ); delete arr; } 

Godbolt: https://godbolt.org/z/95P5d4sfT

Sign up to request clarification or add additional context in comments.

8 Comments

The pointer is just a pointer; it points at the first element of an array. But a pointer doesn't carry any size information; you can't get the size of the array given only the pointer.
That is exactly what I said
When you do structtype* s, what is the s?
Oh wait never mind its just the name
@MadFred — no, that’s not what you said. The array is an array. It’s not a pointer. “Your array is just a pointer” obscures that important distinction.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.