I am trying to create a simple array-expanding function, which creates a new array with the same values as the previous array expanded by a value:
char* test(char array[], int expandBy) {
char newArray[sizeof(array) + expandBy];
strncpy(newArray, array, sizeof(array));
return newArray;
}
However, I am getting the compile-time error expression must have a constant value. All of the answers that I have seen to similar questions suggest using a macro, but I can't use a macro if I don't know the value beforehand.
Does anyone know how I can fix this, or if there is an alternative to this?
strncpywill not add the terminator. Look out for that.newArrayobject that matters, not the scope of its name. Scope is where a name is visible. Lifetime is when an object exists.newArraydeclaration because it uses a run-time value for the dimension. So the reason the OP got the error is actually unrelated to the fact thatsizeof(array)does not produce the size of the “array.”