2013-02-10 66 views
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。

回答

2

的事情是:

  • int (*tgt_s)[cs]指针数组。花几秒钟思考的是,这是一个有点异国情调的指针,因此
  • *tgt_s是一个数组
  • 数组是不可修改的左值

是什么使得它最难理解的是你的方式使用通过cs的C99功能,然后在参数列表中使用它。

如果您想了解更多关于VLA的函数参数,请查看this excellent post

+0

我想知道为什么这个编译。 – 2013-02-10 10:17:41

+0

@ H2CO3使用参数列表中的“cs”为C99。我通过Jens Gustedt链接了一篇文章。 – cnicutar 2013-02-10 10:24:52

+0

我的意思是编译器如何允许增加一个数组。 – 2013-02-10 10:26:24