C语言两个数求和:如何在C语言中追加两个数组(array concat c)

关于C语言两个数求和的问题,在array concat c中经常遇到, 如何将数组 X 和 Y 的元素包含在 C语言中的数组total中?

如何将数组 X 和 Y 的元素包含在 C语言中的数组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]);
51

您现有的代码分配了错误的内存量,因为它根本不考虑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]
3
for (i = 0; i < 4; i++)
{
    total[i]  =h_x[i] = 1;
    total[i+4]=h_y[i] = 2;
}
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;
}
0

我想我会添加这个,因为我发现过去有必要将值附加到 C 数组(如 Objective-C 中的NSMutableArray)。

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;
}

本站系公益性非盈利分享网址,本文来自用户投稿,不代表码文网立场,如若转载,请注明出处

(724)
Cosplay肉:如何传递我的肉 米饭和豆类的价值 从我的玉米煎饼类到肉类类 大米类和豆类类分别
上一篇
Oracle数据库默认端口:OracleRAC数据库jdbc从不同的端口连接
下一篇

相关推荐

发表评论

登录 后才能评论

评论列表(1条)