试图复制数组内容。

[英]Trying to copy contents of array


I am trying to copy the contents from array a to array b. When I test within the function it seems to copy, but when I print out b in the main program, it shows 0s

我试图将数组a中的内容复制到数组b中,当我在函数中进行测试时,它看起来是复制的,但是当我在主程序中打印b时,它显示了0。

void array_copy(int a[], int b[], int n) {

for (int j = 0; j < n; j++) {
    b = a;
    //printf("%d\n", *b);
    a++;
    b++;
}

and then when I try and print to test outside, I get 0s

当我试着打印出来在外面测试时,我得到了0。

printf("%d", *b);

Any ideas why I am getting 0 instead of what should be in there. (I have made sure array a does contain non zero values)

知道为什么我得到0而不是应该在那里。(我已经确保数组a包含非零值)

2 个解决方案

#1


2  

b = a;

This line makes the pointer b points to the same place where a points to. What you want (copying the contents) should be:

这条线使指针b指向一个指向的地方。你想要的(复制内容)应该是:

*b = *a;

#2


1  

try this:

试试这个:

void array_copy(int a[], int b[], int n) 
{
    int j=0;
    for ( j = 0; j < n; j++) 
    {
        *b = *a; /*  * will give the value */
        printf("%d\n", *b);
        a++;
        b++;
    }
}

int main ( void )
{
    int a[5] = {1,2,3,4,5};
    int b[5];
    array_copy (a, b, 5 );
    return ( 0 );
}

注意!

本站翻译的文章,版权归属于本站,未经许可禁止转摘,转摘请注明本文地址:https://www.itdaan.com/blog/2015/01/20/fd2366093f663100243722061e5fba09.html



 
粤ICP备14056181号  © 2014-2020 ITdaan.com