Reputation: 105
i have const char array and i want to change (sort) valuables inside it. SO i need to create a second one which will not be const (i believe there is no other way). The field has fixed number of columns (2), but not number of rows.
So first i tried this:
count = 0; // count how many rows (i have 100% Null at the end)
while(arrayConst[count][0]){
count ++;
}
char* arrayEditable [count][2]; // deslare new field
for(i = 0; i < count; i++){ // and copy everithing to new one
arrayEditable[i][0] = (char*)arrayConst[i][0];
arrayEditable[i][1] = (char*)arrayConst[i][1];
}
This works pretty well (program is running) except i have this message from compilator:
ISO C++ forbids variable length array ‘arrayEditable’
So it looks like i need to allocate that dynamicly. I tried something like this:
count = 0;
while(arrayConst[count][0]){
count ++;
}
char (*arrayEditable)[2];
arrayEditable = (char (*)[2])malloc(count * 2 * sizeof(char));
for(i = 0; i < count; i++){
arrayEditable[i][0] = arrayConst[i][0];
arrayEditable[i][1] = arrayConst[i][1];
}
but it still doesnt work - now im getting some weird info:
expected ‘const char *’ but argument is of type ‘char’|
and i also believe, that i alocated that field wrong, because i dont know, how long will that string be so it can overflow (but maybe i get it wrong). So how should i duplicate that field? I just need not const field to change values in it (sort);
Upvotes: 0
Views: 45
Reputation:
You tagged this C and you are using a variable-length array (VLA) which is a C feature. The style of the code is also C, and definitely not C++. Yet your compiler error suggests that you are trying to compile C code with a C++ compiler, which is wrong, and you should immediately cease doing so.
Compile your code with a C compiler and the error will be gone.
Oh, and while we're at it: do not ever cast the return value of malloc()
! Simply don't.
Upvotes: 1