storage size of array isnt known error

i am not really sure what to do.
char a[];
I thought that this was the way to declare an unknown array?

I was initially trying to convert the string into an array of chars.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <iostream>
#include <string>
#include <typeinfo>


using namespace std;


char str_char(string s){
	int len = s.length();
	char array[len];
	for (int i=0; i < len; i++){
		array[i] = s[i];
	}
	return array[len];
}


int main(){
	string s = "test";
	char a[];
	a = str_char(s);
	cout << a;
}


which gives the error of:
test.cpp:21:9: error: storage size of ‘a’ isn’t known
Last edited on
1
2
	int len = s.length();
	char array[len];


There are no VLAs in C++, so this is not legal code. Array size must be specified by a compile-time constant.


char a[];

Also not legal code.

Use a vector or do some research on dynamic allocation of arrays.
A string is already an array of chars. You can obtain a pointer to the first element of that array with &s[0], s.data(), or s.c_str().

If you want to copy them out to a vector, it's just
vector<char> a(s.begin(), s.end());
Last edited on
Topic archived. No new replies allowed.