【发布时间】:2013-12-16 17:44:44
【问题描述】:
我有 const char 数组,我想在其中更改(排序)贵重物品。所以我需要创建第二个不是 const 的(我相信没有其他方法)。 该字段具有固定的列数 (2),但不是行数。
所以我首先尝试了这个:
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];
}
这很好用(程序正在运行),除了我从编译器收到这条消息:
ISO C++ forbids variable length array ‘arrayEditable’
所以看起来我需要动态分配它。 我尝试过这样的事情:
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];
}
但它仍然不起作用 - 现在我得到了一些奇怪的信息:
expected ‘const char *’ but argument is of type ‘char’|
而且我也相信,我错误地分配了该字段,因为我不知道该字符串要多长时间才能溢出(但也许我弄错了)。 那么我应该如何复制该字段?我只是不需要 const 字段来更改其中的值(排序);
【问题讨论】:
-
我刚刚发现,我可以立即更改该 const 数组,所以我根本不需要欺骗它。我以为你不能改变成本数组,但看起来你可以....
标签: c arrays duplicate-data