1
我无法理解为什么递增下面的pnArryCpy中的指针不正确。我想了解如何用指针表示法以不同的方式复制数组,但我需要了解这有什么问题(例如,(* tgt_s)++;
其中int (*tgt_s)[cs]
),以及为什么tgt_s
是左值(例如,tgt_s++
有效)但*tgt_s
不是(真的)一个左值。通过指针表示法写入二维数组
int main(void)
{
int arr1[2][4] = { {1, 2, 3, 4}, {6, 7, 8, 9} };
int arr2[2][4];
pnArrCpy(4, arr1, arr2, arr2+2); // copies 2d array using pointer notation
// - this is where the problem is.
printarr(2, 4, arr2); // this just prints the array and works fine - not at issue
putchar('\n');
return 0;
}
void pnArrCpy(int cs, int (*src)[cs], int (*tgt_s)[cs], int (*tgt_e)[cs])
{
while (tgt_s < tgt_e)
{
**tgt_s=**src;
(* tgt_s)++; // older versions of gcc warn "target of assignment not really
// an lvalue", latest versions throw an error
(* src)++; // but no errors are runtime
}
return;
}
// trucated rest of program since it's not relevant, just the function for printing
// the array
在旧的GCC,程序编译,并显示正确的结果,即:
1 2 3 4
6 7 8 9
的Mac OS 10.8.2
GCC 4.7.2给我的错误
GCC 4.2。 1只给了我警告
谢谢!
编辑:我使用可变长度数组的原因:此功能是另一个程序的一部分,而这一个只是我用来解决pnArrCpy故障的驱动程序。在实际的程序中,数组的尺寸和内容是用户定义的,因此使用VLA。
我想知道为什么这个编译。 – 2013-02-10 10:17:41
@ H2CO3使用参数列表中的“cs”为C99。我通过Jens Gustedt链接了一篇文章。 – cnicutar 2013-02-10 10:24:52
我的意思是编译器如何允许增加一个数组。 – 2013-02-10 10:26:24