13

How can I include the elements of array X and Y in to array total in C language ? can you please show with an example.

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]);
Justin k
  • 1,104
  • 5
  • 22
  • 33

7 Answers7

57

Your existing code is allocating the wrong amount of memory because it doesn't take sizeof(float) into account at all.

Other than that, you can append one array to the other with 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]
Jon
  • 428,835
  • 81
  • 738
  • 806
  • 1
    Thanks a lot for showing me with an example. It was very helpful – Justin k Aug 13 '12 at 10:43
  • 4
    [You should not cast the return of malloc](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Eregrith Aug 13 '12 at 11:34
  • 1
    ...and it's better not to mention the type in sizeof: `float* total = malloc(8 * sizeof(*total));` – Déjà vu Dec 12 '15 at 10:01
  • After the last memcpy is `total` seen as a bigger array or a `2x4` matrix? – elmazzun Feb 14 '16 at 18:59
  • @elmazzun not sure what you mean by "bigger array"? Anyway, `total` is not an array because it wasn't created with array syntax. The difference might seem small but it definitely exists. – Jon Feb 14 '16 at 19:29
  • Shouldn't you take into account the `sizeof(float)` when doing `total + 4`? – Dragas Mar 25 '19 at 20:27
  • The memcpy URL link above returns a 404. Here's the updated link for [memcpy](https://cplusplus.com/reference/cstring/memcpy/) – chikega Feb 12 '23 at 16:19
3
for (i = 0; i < 4; i++)
{
    total[i]  =h_x[i] = 1;
    total[i+4]=h_y[i] = 2;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70
  • 1
    Only works for the specific example in the question, but not in the general case. – stakx - no longer contributing Aug 13 '12 at 21:53
  • @stakx : I do not think most benefits can make a generic function also, I think the question in this case that the function is required there is no generic. – BLUEPIXY Aug 14 '12 at 08:46
  • @BLUEPIXY - definitely the two input arrays having the same number of elements is too special. Yet your solution specifically takes advantage of that. –  Jan 28 '19 at 18:22
0

I thought I'd add this because I've found it necessary in the past to append values to a C array (like NSMutableArray in Objective-C). This code manages a C float array and appends values to it:

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;
}
Rob Sanders
  • 5,197
  • 3
  • 31
  • 58
0

may be this is simple.

#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]);}
}
MD XF
  • 7,860
  • 7
  • 40
  • 71
kush rami
  • 16
  • 1
0

Here a solution to concatenate two or more statically-allocated arrays. Statically-allocated arrays are array whose length is defined at compile time. The sizeof operator returns the size (in bytes) of these arrays:

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

We can use the operator sizeof to build a set of macros that will concatenate two or more arrays, and possibly returns the total array length.

Our macros:

#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

An example of use:

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

However, thanks to the way we defined our macros, we can concatenate any type of objects as long as sizeof returns their size. For instance:

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

Using constant literals, one can also these macros to concatenate constants, results from functions, or even constant arrays:

// 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}));
Fuujuhi
  • 313
  • 3
  • 8
0

i like the answer from jon. In my case i had to use a static solution. So if you are forced to not use dynamic memory allocation:

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]);
}
saggzz
  • 301
  • 3
  • 9
0

Why not use simple logic like this?

enter image description here

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

Resultant array size must be equal to the size of array a and b.

Source: C Program To Concatenate Two Arrays

Satish
  • 173
  • 1
  • 9