簡體   English   中英

發現這個 function 有什么問題?

[英]Find what's wrong with this function?

我認為這段代碼沒有問題。

void copydata(uint8_t *datato, uint8_t *datafrom, int size)
{
    uint8_t *CurrentAddress = datafrom;
    uint8_t *StopAddress = datafrom + size;
    
    for(;CurrentAddress <= StopAddress;CurrentAddress++)
        *CurrentAddress = *datafrom++;

}

function 是錯誤的。

對於初學者來說,它應該被聲明為

void copydata( uint8_t *datato, const uint8_t *datafrom, size_t size );

或者甚至更好地聲明它

uint8_t * copydata( uint8_t *datato, const uint8_t *datafrom, size_t size );

其次,這個循環中的條件

for(;CurrentAddress <= StopAddress;CurrentAddress++)

應該看起來像

for( ; CurrentAddress < StopAddress; CurrentAddress++ )

或者

for( ; CurrentAddress != StopAddress; CurrentAddress++ )

最后你試圖將數組復制到自身

uint8_t *CurrentAddress = datafrom;
//...
*CurrentAddress = *datafrom++;

function可以看如下方式

uint8_t * copydata( uint8_t *datato, const uint8_t *datafrom, size_t size )
{
    
    for ( const uint8_t *StopAddress = datafrom + size; datafrom != StopAddress; ++datafrom )
    {
        *datato++ = *datafrom;
    }

    return datato;
}     

這是一個演示程序。

#include <stdio.h>
#include <stdint.h>

uint8_t * copydata( uint8_t *datato, const uint8_t *datafrom, size_t size )
{
    
    for ( const uint8_t *StopAddress = datafrom + size; datafrom != StopAddress; ++datafrom )
    {
        *datato++ = *datafrom;
    }

    return datato;
} 

int main(void) 
{
    enum { N = 10 };
    uint8_t a[N];
    uint8_t b[N / 2] = { 1, 2, 3, 4, 5 };
    uint8_t c[N / 2] = { 5, 4, 3, 2, 1 };
    
    copydata( copydata( a, b, N / 2 ), c, N / 2 );
    
    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%d ", a[i] );
    }
    
    putchar( '\n' );
    
    return 0;
}

程序 output 是

1 2 3 4 5 5 4 3 2 1

另一種方法是使用在 header <string.h>中聲明的標准 function memcpy 例如

#include <stdio.h>
#include <stdint.h>
#include <string.h>

uint8_t * copydata( uint8_t *datato, const uint8_t *datafrom, size_t size )
{
    return ( uint8_t * )memcpy( datato, datafrom, size * ( sizeof( uint8_t ) ) ) + size;   
} 

int main(void) 
{
    enum { N = 10 };
    uint8_t a[N];
    uint8_t b[N / 2] = { 1, 2, 3, 4, 5 };
    uint8_t c[N / 2] = { 5, 4, 3, 2, 1 };
    
    copydata( copydata( a, b, N / 2 ), c, N / 2 );
    
    for ( size_t i = 0; i < N; i++ )
    {
        printf( "%d ", a[i] );
    }
    
    putchar( '\n' );
    
    return 0;
}

程序 output 與上圖相同。

只有初始化是錯誤的......

void copydata(uint8_t *datato, uint8_t *datafrom, int size)
{
    uint8_t *CurrentAddress = datato;      // Needs to be datato, not datafrom
    uint8_t *StopAddress = datato + size;  // Needs to be datato, not datafrom
    
    for(;CurrentAddress <= StopAddress;CurrentAddress++)
        *CurrentAddress = *datafrom++;

}

工作崗位...

也就是說,這是特別糟糕的代碼。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM