组合字节数组以接受可变数量的参数

时间:2016-04-27 19:21:06

标签: c arrays concat variadic-functions

如何组合字节数组以接受c?

中的可变数量的参数(可变参数函数)
typedef struct {
    unsigned char *data; 
    int length;          
} bytes;

// Problem in here how to combine byte arrays 
// for accepts a variable number of arguments
bytes bytesConcat(bytes fmt, ...) {
    return b1 + b2 + ...b(n)
}

static unsigned char src1[] = { 1,2 }; 
static unsigned char src2[] = { 3,4 };

void main() {
    bytes b1, b2;

    b1.data = src1;
    b1.length = sizeof(src1);
    b2.data = src2;
    b2.length = sizeof(src2);

    // call byteConcat with passing two arguments
    // result1 expected is 1,2,3,4
    bytes result1 = bytesConcat(b1, b2);
}

提前致谢

2 个答案:

答案 0 :(得分:0)

@ 2501,谢谢你指出。

unsigned char *appendBytes(int count, int *size, unsigned char *arg1, ...) {
    int i, total;
    unsigned char *tmp, *pd, *argn;
    va_list ap;

    if ((arg1 != NULL) && (count > 0)) {
        total = 0;
        for (i = 0; i < count; i++) {
            total += size[i];
        }

        if (total > 0) {
            tmp = (unsigned char *)malloc((size_t)(total + 1));
            if (tmp != NULL) {
                memset(tmp, null, sizeof(tmp));
                pd = tmp;

                va_start(ap, arg1);
                memcpy(pd, arg1, size[0]);
                pd += size[0];
                for (i = 1; i < count; i++) {
                    argn = va_arg(ap, unsigned char*);
                    memcpy(pd, argn, size[i]);
                    pd += size[i];
                }
                va_end(ap);
                return tmp;
            }
        }
    }
    return NULL;
}

void main(){
    static unsigned char c1[] = { 1};
    static unsigned char c2[] = { 2, 3 };
    static unsigned char c3[] = { 4, 5, 6, 7, 8, 9, 10 };

    int size[] = { sizeof(c1), sizeof(c2), sizeof(c3) };
    unsigned char *result = appendBytes(3, size, c1, c2, c3);

    // show output : 1 2 3 4 5 6 7 8 9 10
    for (i = 0; i < sizeof(c1) + sizeof(c2)+ sizeof(c3); i++) {
        printf("%u ", result[i]);
    }

    getchar();
}

答案 1 :(得分:-2)

使用动态数组/动态内存分配:malloc() calloc() realloc() free()

初始化时使用malloc()calloc()为阵列分配内存。如果数组变大或变小,则使用realloc()分配新的内存量

示例如下:Dynamic Array in C - Is my understanding of malloc/realloc correct?

double* data = (double*)malloc(10*sizeof(double));

 for (j=0;j<10;j++)
 {`
      data[j]= ((double)j)/100;
      printf("%g, ",data[j]);
 }

 printf("\n");

 data = (double*)realloc(data,11*sizeof(double));

 for (j=0;j<11;j++)
 {
     if (j == 10){ data[j]= ((double)j)/100; }
     printf("%g, ",data[j]);
 }

 free((void*) data);

另见https://www.happybearsoftware.com/implementing-a-dynamic-array

由于可变参数功能 2501的评论是正确的。使用stdarg.h并查看例如例如维基百科(https://en.wikipedia.org/wiki/Variadic_function

要在C中连接数组,请参阅 How can I concatenate two arrays in C?