簡體   English   中英

如何在C語言中追加兩個數組?

[英]How to append two arrays in C language?

如何在 C 語言中將數組 X 和 Y 的元素包含到數組total中? 你能舉個例子嗎?

X = (float*) malloc(4);
Y = (float*) malloc(4);
total = (float*) malloc(8);

for (i = 0; i < 4; i++)
{
    h_x[i] = 1;
    h_y[i] = 2;
}

//How can I make 'total' have both the arrays x and y
//for example I would like the following to print out 
// 1, 1, 1, 1, 2, 2, 2, 2

for (i = 0; i < 8; i++)
    printf("%.1f, ", total[i]);

您現有的代碼分配了錯誤的內存量,因為它根本不考慮sizeof(float)

除此之外,您可以使用memcpy將一個數組附加到另​​一個數組:

float x[4] = { 1, 1, 1, 1 };
float y[4] = { 2, 2, 2, 2 };

float* total = malloc(8 * sizeof(float)); // array to hold the result

memcpy(total,     x, 4 * sizeof(float)); // copy 4 floats from x to total[0]...total[3]
memcpy(total + 4, y, 4 * sizeof(float)); // copy 4 floats from y to total[4]...total[7]
for (i = 0; i < 4; i++)
{
    total[i]  =h_x[i] = 1;
    total[i+4]=h_y[i] = 2;
}

當您知道它們的大小時連接兩個 C 數組的方法。

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

#define ARRAY_CONCAT(TYPE, A, An, B, Bn) \
(TYPE *)array_concat((const void *)(A), (An), (const void *)(B), (Bn), sizeof(TYPE));

void *array_concat(const void *a, size_t an,
               const void *b, size_t bn, size_t s)
{
    char *p = malloc(s * (an + bn));
    memcpy(p, a, an*s);
    memcpy(p + an*s, b, bn*s);
    return p;
}

// testing
const int a[] = { 1, 1, 1, 1 };
const int b[] = { 2, 2, 2, 2 };

int main(void)
{
    unsigned int i;

    int *total = ARRAY_CONCAT(int, a, 4, b, 4);

    for(i = 0; i < 8; i++)
        printf("%d\n", total[i]);

    free(total);
    return EXIT_SUCCCESS;
}

我想我會添加這個,因為我發現過去有必要將值附加到 C 數組(如 Objective-C 中的NSMutableArray )。 此代碼管理一個 C float組並向其附加值:

static float *arr;
static int length;

void appendFloat(float);

int main(int argc, const char * argv[]) {

    float val = 0.1f;
    appendFloat(val);

    return 0;
}

void appendFloat(float val) {
    /*
     * How to manage a mutable C float array
     */
    // Create temp array
    float *temp = malloc(sizeof(float) * length + 1);
    if (length > 0 && arr != NULL) {
        // Copy value of arr into temp if arr has values
        memccpy(temp, arr, length, sizeof(float));
        // Free origional arr
        free(arr);
    }
    // Length += 1
    length++;
    // Append the value
    temp[length] = val;
    // Set value of temp to arr
    arr = temp;
}

可能這很簡單。

#include <stdio.h>

int main()
{
    int i,j,k,n,m,total,a[30],b[30],c[60];
    //getting array a
    printf("enter size of array A:");
    scanf("%d",&n);
    printf("enter %d elements \n",n);
    for(i=0;i<n;++i)
    {scanf("%d",&a[i]);}

    //getting aaray b
    printf("enter size of array b:");
    scanf("%d",&m);
    printf("enter %d elements \n",m);
    for(j=0;j<m;++j)
    {scanf("%d",&b[j]);}

    total=m+n;
    i=0,j=0;

    //concating starts    
    for(i=0;i<n;++i)
    {
       c[i]=a[i];
    }
    for(j=0;j<m;++j,++n)
    {
       c[n]=b[j];
    }

    printf("printing c\n");
    for(k=0;k<total;++k)
    {printf("%d\n",c[k]);}
}

這是連接兩個或多個靜態分配數組的解決方案。 靜態分配的數組是其長度在編譯時定義的數組。 sizeof運算符返回這些數組的大小(以字節為單位):

char Static[16];               // A statically allocated array
int n = sizeof(Static_array);  // n1 == 16

我們可以使用運算符sizeof來構建一組宏,這些宏將連接兩個或多個數組,並可能返回數組的總長度。

我們的宏:

#include <string.h>

#define cat(z, a)          *((uint8_t *)memcpy(&(z), &(a), sizeof(a)) + sizeof(a))
#define cat1(z, a)         cat((z),(a))
#define cat2(z, a, b)      cat1(cat((z),(a)),b)
#define cat3(z, a, b...)   cat2(cat((z),(a)),b)
#define cat4(z, a, b...)   cat3(cat((z),(a)),b)
#define cat5(z, a, b...)   cat4(cat((z),(a)),b)
// ... add more as necessary
#define catn(n, z, a ...)  (&cat ## n((z), a) - (uint8_t *)&(z)) // Returns total length

使用示例:

char      One[1]   = { 0x11 };
char      Two[2]   = { 0x22, 0x22 };
char      Three[3] = { 0x33, 0x33, 0x33 };
char      Four[4]  = { 0x44, 0x44, 0x44, 0x44 };
char      All[10];
unsigned  nAll = catn(4, All, One, Two, Three, Four);

然而,由於我們定義宏的方式,我們可以連接任何類型的對象,只要sizeof返回它們的大小。 例如:

char      One      = 0x11;                                // A byte
char      Two[2]   = { 0x22, 0x22 };                      // An array of two byte
char      Three[]  = "33";                                // A string ! 3rd byte = '\x00'
struct {
    char  a[2];
    short  b;
}         Four     = { .a = { 0x44, 0x44}, .b = 0x4444 }; // A structure
void *    Eight    = &One;                                // A 64-bit pointer
char      All[18];
unsigned  nAll     = catn(5, All, One, Two, Three, Four, Eight);

使用常量字面量,我們還可以使用這些宏來連接常量、函數的結果,甚至是常量數組:

// Here we concatenate a constant, a function result, and a constant array
cat2(All,(char){0x11},(unsigned){some_fct()},((uint8_t[4]){1,2,3,4}));

我喜歡喬恩的回答。 就我而言,我不得不使用靜態解決方案。 因此,如果您被迫不使用動態內存分配:

int arr1[5] = {11,2,33,45,5};
int arr2[3] = {16,73,80};
int final_arr[8];

memcpy(final_arr, arr1, 5 * sizeof(int));
memcpy(&final_arr[5], arr2, 3 * sizeof(int));

for(int i=0; i<(sizeof(final_arr)/sizeof(final_arr[0]));i++){
    printf("final_arr: %i\n", final_arr[i]);
}

為什么不使用這樣的簡單邏輯?

在此處輸入圖片說明

#include<stdio.h>  
  
#define N 5  
#define M (N * 2)  
  
int main()  
{  
    int a[N], b[N], c[M], i, index = 0;  
  
    printf("Enter %d integer numbers, for first array\n", N);  
    for(i = 0; i < N; i++)  
        scanf("%d", &a[i]);  
  
    printf("Enter %d integer numbers, for second array\n", N);  
    for(i = 0; i < N; i++)  
            scanf("%d", &b[i]);  
  
    printf("\nMerging a[%d] and b[%d] to form c[%d] ..\n", N, N, M);  
    for(i = 0; i < N; i++)  
        c[index++] = a[i];  
  
    for(i = 0; i < N; i++)  
        c[index++] = b[i];  
  
    printf("\nElements of c[%d] is ..\n", M);  
    for(i = 0; i < M; i++)  
        printf("%d\n", c[i]);  
  
    return 0;  
} 

結果數組大小必須等於數組 a 和 b 的大小。

來源:連接兩個數組的 C 程序

暫無
暫無

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

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