簡體   English   中英

如何遍歷數組以將它們復制到uint32_t類型的另一個數組中?

[英]How to iterate through arrays to copy them into another array of type uint32_t?

我創建了一個C程序,該程序由整數數組結構States [2]組成 我還需要一個名為store的uint32_t類型數組。 我只想將數組狀態[0]的內容復制到store [0]中,並將狀態[1]的內容復制到store [1]中。 我將這種方法用於char數組,它似乎有效。 我的代碼如下所示:

 #include <stdlib.h>
 #include <stdio.h>

 int main()
 {
     uint32_t *store[2];
     int i;
     int *states[2];
     int states[0] = {1,0,0,1};
     int states[1] = {0,0,0,2};

     for (i = 0; i < 3; i++)
     {
        store[i] = states[i];
        i++;
     }
 }

但是代碼沒有執行,並說我聲明的數組格式無效。我不確定這是否是正確的方法。 有人可以幫我這個忙。

我已經重寫了您的示例-強制使用數組的大小-在這種情況下,它可以正常工作。

編輯-添加printf調用以顯示數組存儲的內容。

 #include <stdlib.h>
 #include <stdio.h>

 int main()
 {
     int store[3][4];
     int i;
     int states[3][4] = {{1,0,0,1},{0,0,0,2}};

     for(i=0; i<3; i++)
     {
        printf( "store[%d] = ", i );
        for( int inner = 0; inner < 4; inner++ )
        {
           store[i][inner] = states[i][inner];
           printf( "%d ", store[i][inner] ); 
        }
        printf( "\n" );
     }

    return( 0 );   

}

在數組中創建指針時,您確實需要分配然后復制。

您的代碼中有兩個問題,

第一,

int *states[2];
int states[0] = {1,0,0,1};
int states[1] = {0,0,0,2};

有問題。 訪問變量時,不提及類型,僅在定義時才需要。 因此,使用int states[0]..[1] 是無效的。

然后,第二,

states[0] = {1,0,0,1};

state[0]的類型為int * ,並且您嘗試使用括號括起來的int初始化列表進行初始化。 那也不是正確的事情。

您可以修改代碼以在訪問數組元素時刪除類型並使用復合文字,最后看起來類似於以下內容

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>   //added for uint32_t 

 int main(void)        //corrected signature
 {
     uint32_t *store[2];
     int i;
     int *states[2];
     states[0] = (int []){1,0,0,1};     //compound literal, C99 and above
     states[1] = (int []){0,0,0,2};

     for (i = 0; i < 2; i++)           //bound corrected
     {
        store[i] = states[i];
                                       //i++; remove this, you're incrementing twice
     }
 }

暫無
暫無

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

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