Concatenating 2 arrays without memcpy - c

Suppose I ve
int *a,*b;
a= malloc(5*sizeof(int));
b= malloc(5*sizeof(int));
and subsequently assign values.
Let a - 1, 2, 3, 4, 5
b - 6, 7, 8, 9, 10
Is there a method to concatenate both these malloced arrays without using further malloc,realloc or memcpy? There shud not be a malloc of 10 locations!
I must be able to get a[8]=9 after executing, without the overhead of moving the arrays.
The language is C

a= malloc(5*sizeof(int));
You only allocated 5 ints to a, so no, you can't do it without some form or memory allocation (malloc / realloc), since a[8] would be illegal to begin with.
I must be able to get a[8]=9 after executing, without the overhead of
moving the arrays
Since since you are working with contiguous memory regions (which you are calling arrays) you will always have some overhead when moving elements around. If you don't need to access elements by their indexes just use linked lists.

If you don't need strict array indexing, you could make a pseudo-linked-list (I know there's a name for this data type but I can't remember it right now):
struct listish {
int *arr
size_t size;
struct listish *next;
};
The "indexing" function would look like this:
int *index(struct listish *list, size_t i)
{
if(list == NULL) return NULL; // index out of bounds
if(i < list->size) return list->arr + i; // return a pointer to the element
else return index(list->next, i - list->size); // not in this array - go to next node
}
The idea is to combine the in-place reordering of a linked list with the contiguous space of an array. In this case, index(list, 4) would return &a[4], and index(list, 5) would return &b[0], simulating continuous indexing without reallocating and moving your entire array - all you need to do is allocate a few small struct listish objects and set them up properly, a task I leave to you.

What you ask can't be done.
You have, maybe, another option.
Just allocate space for 10 values, and make b point to the correct element
int *a = malloc(10 * sizeof *a);
/* error checking missing */
int *b = a + 5;
a[0] = 1; a[1] = 2; a[2] = 3; a[3] = 4; a[4] = 5;
b[0] = 6; b[1] = 7; b[2] = 8; b[3] = 9; b[4] = 10;
printf("a[8] is %d\n", a[8]);

Related

Making two arrays occupy same memory region in C language

Arrays in C are actually constant pointers. The pointer to the first element of an array is a constant. Therefore it seems impossible to assign an address value to the array pointer pointer pointing the firs element of the array.
But in some situations it might be useful to have two arrays point to the same location in memory.
So how can I make two arrays point to the same location in such fashion :
int a[10];
int b[10];
a = b; // Not possible
What is below seems to be a valid solution. But, are there alternatives?
int *a;
int *b;
int c[10];
a = c; // If you change the value "a" points to
b = c; // it will be observed on "b"
a[2] = 5;
printf("Output is %d", b[2]);
>> Output is 5
Arrays behave like pointers to their first element, but you can't reassign them:
int a[] = { 1, 2 };
int b[] = { 3, 4 };
b = a; // compilation error: b is constant
The reason is their address, being known at compile time, is stored in a read-only segment of the program, and writing in a read-only segment would be a segmentation fault.
A pointer is a type which contains an address, it can be assigned at runtime.
If you don't know at compile-time how much memory you need, you can ask some to your system with dynamic allocation:
int * integers = malloc(sizeof(int) * 3); // dynamic array of size 3
// or
int * integers = malloc(sizeof(* integers) * 3);
If you want 2 arrays to point to the same memory:
char * interval1 = malloc(sizeof(char) * 2); // sizeof() useless here, char is defined as 1 byte
interval1[0] = 'A'; // equivalent to *(p + 0) = 'A'
interval1[1] = 'Z'; // equivalent to *(p + 1) = 'Z'
char * interval2 = interval1;
But the interest is rather limited if both variables are in the same function.
I didn't add checks, but you should always check for NULL after allocation, and free() when you don't need the memory anymore.
TDLR: if you need to reassign an address, don't use array-type, but pointer-type, it's made to be dynamic.

How to initialize a array with determined values?

I'm trying to prepare a value list. Briefly:
int x = 5;
int y = 9;
int z = 43;
int myarray[80] = {x, y, z};
But as you know, it's a mistake. I have too many value and they have a special order. The array is like this at the moment:
int x = 5;
int y = 9;
int z = 43;
int myarray[80];
myarray[1] = x;
myarray[2] = y;
myarray[3] = z;
when I want to insert a value between y and z, I need to change all values order by plus 1 after z.
If you want to "insert" new elements into your array, you need to make space for it. That means you need to move the latter elements one step "up" in the array.
You can either do this moving by using a loop like
for (size_t i = 79; // Index of last element
i > 2; // The index of the element you want to insert *before*
++i)
{
myarray[i] = myarray[i - 1]; // Move previous element up one step
}
Then you can "insert" the new value at the wanted position
myarray[2] = new_value;
Instead of an explicit loop you could also use memmove:
// Move element 2 to become element 3, element 3 will become element 4, etc.
memmove(&myarray[3], &myarray[2], sizeof myarray - sizeof myarray[0] * 2);
myarray[2] = new_value;
[Note that the above memmove call is just written without testing, I could have gotten the size wrong]
No matter what you do, an explicit loop or calling memmove, you will lose the last element in the array (at index 79 for an 80-element array).
If you're going to do insertions like this a lot, or if you don't want to loose any elements, then an array is probably not the correct container type. A linked list would be a lot better.
In C you cant add or remove the element from the array. You need to write your own functions like this
void insert(void *arr, void *val, size_t pos, size_t arraySize, size_t elemSize)
{
char *startRef = (char *)arr + pos * elemSize;
memmove(startRef + elemSize, startRef, (arraySize - pos - 1) * elemSize);
memcpy(startRef, val, elemsize);
}
First of all, what do you mean by insert. If by insert the size of the array changes (from 80 to 81), then you
1) need to use dynamic memory allocated arrays: int* myarray = (int*)malloc(80 * sizeof(int));
2) before insert, you need to increase the size: myarray = (int*)realloc(myarray, 81*sizeof(int));
3) then move the content of the memory: start from 81 -- downwards
If you want to keep the size of your array to 80, then go to step 3.
If your max value is less than 80 you can use the index of array to store a flag 0/1 (present/not present)
unsigned char myarray[80];
memset(myarray,0,sizeof(myarray));
myarray[x]=1;
myarray[y]=1;
myarray[z]=1;
/* x,y,z... must be <80 */
So array is always sorted without moving array items.
This is correct syntax for array initialization with values:
var a = new int[] {x, y, z};

Dynamically creating a contiguous 5D array? [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I am working with a very large 5D array that I need to read into contiguous memory (another 5D array). I cannot place the array on the stack because it is too large and creates seg faults. What I've done is to create a 5D array dynamically with malloc however I've found that it is not contiguous memory. Is there an elegant solution to this or is it going to be messy no matter what?
From Jens Gustedt: Don't use fake matrices.
Allocate a 5-dimensional matrix with dimensions A x B x C x D x E (dimensions aren't required to be known at compile time) like so:
float (*matrix5d)[B][C][D][E] = malloc(sizeof(float[A][B][C][D][E]));
Release the memory with a single call to free.
free(matrix5d);
Note that the above requires C99 or higher for variable-length arrays.
Being represented via a contiguous chunk of memory is one of the distinguishing properties of a C array. Multidimensional arrays are arrays of arrays, and therefore contiguous the same as any other array, so if you want a genuine 5D array then you certainly do need contiguous memory for it. As some of the other answers have observed, to ensure that you get a contiguous block of memory, you must allocate the whole thing at once.
Although you can form data structures consisting of arrays of pointers to [[arrays of pointers to [arrays of pointers to ...]] arrays, these are not the same thing at all, just as pointers are not arrays. You can use the indexing operator, [], with such data structures in the same way that you can do with multi-dimensional arrays, but that doesn't make them the same thing.
#EvelynParenteau suggested simulating your 5D array with a 1D array, and indeed that's one way to satisfy your contiguity requirement. You could even write macros to make indexing into such an array easier.
But as long as you are using at least C99, you can dynamically allocate a genuine 5D array. The general form might look something like this:
void allocate_5d(unsigned dim1, unsigned dim2, unsigned dim3, unsigned dim4,
unsigned dim5, double (**aptr)[dim2][dim3][dim4][dim5]) {
*aptr = malloc(dim1 * sizeof(**aptr));
}
It would be used like this:
void do_something(unsigned dim1, unsigned dim2, unsigned dim3, unsigned dim4,
unsigned dim5) {
double (*array)[dim2][dim3][dim4][dim5];
allocate_5d(dim1, dim2, dim4, dim4, dim5, &array);
if (!array) {
// Handle allocation failure ...
}
array[0][0][0][0][0] = 42;
// ...
free(array);
}
If dimensions 2 - 5 are compile-time constants, then you can even do a this (slightly differently) in C90, but the variation presented above depends on variable-length arrays, which were new in C99.
There is a way to make the memory contiguous, but whether its elegant or messy I'll leave up to you ;)
First, let's consider the case of a 1 dimensional array. In this case, it's trivial to get contiguous memory; the memory you get from malloc will be contiguous. It seems simple enough, but we're going to later use this fact to get a 5 dimensional contiguous array.
Now, let's consider a 2 dimensional array that is M by N in size. Here's one way of creating one (assuming we're using floats).
float** array2d = malloc(M * sizeof(float*));
for (int i = 0; i < M; i++) {
array2d[i] = malloc(N * sizeof(float));
}
Strictly speaking, this is not a two dimensional array, it's an array of arrays. Now, we can access elements of array2d like array2d[0][0], array2d[0][1] etc. Conceptually this is very nice, but as you've noted, we don't necessarily have contiguous memory since we did multiple calls to malloc. What we need is a way to allocate all of the memory necessary to store M*N floats in one call to malloc.
float* array2d = malloc(M * N * sizeof(float));
Note that in this form, array2d is float* instead of float**, i.e. it's an array of floats, not an array of arrays of floats. So, we can't do array2d[0][0] any more. How do we now index this array?
It's entirely up to us to decide how this 2 dimensional array is laid out in memory. Let's say that M is the "width" of the array (meaning the number of elements in a row) and that N is the "height" of the array (meaning the number of rows in the array). Also, let's just say that the first M entries in the array are the first row, the next M entries are the second row, etc. So to read the entry at row y, column x, we would do this:
float data = array2d[y * M + x];
Say we want element (0, 0). Then y * M + x simply becomes 0, so we're good. Now say we want element (1, 0) (i.e. the first element in the second row). Then, y * M + x becomes M, which as we've decided above is where the second row starts.
We can generalize this approach to higher dimensions. Let's say we have a three dimensional array of size L by M by N. You can think of this as L two dimensional arrays laid out sequentially in memory, all of size M by N. Then, to access element (x, y, z) we would do:
float data = array3d[z * (M * N) + y * (M) + x];
Conceptually you can think of this as skipping the first z two dimensional arrays, then skipping the first y rows of that array, and then going to the xth element of that row. For more dimensions, there are more multiplicative terms when indexing, but the approach is fundamentally the same.
One way of thinking about it is to use malloc to allocate a 1d array of 4d arrays, because fundamentally malloc can only allocate 1d arrays, and an N-d array is just 1d array of (N-1)-d arrays.
However, just like any array allocated by malloc, the "array object" is actually a pointer, so you shouldn't use sizeof() to get the size of the array.
#include <stdio.h>
#include <stdlib.h>
typedef int Array_4D_Type[4][3][2][1];
int main(void) {
Array_4D_Type *arr = malloc(5 * sizeof(Array_4D_Type));
// ^^^^^^^^^^^^^^^^ here, allocate a length-5 vector of 4d array type
int *p = &arr[0][0][0][0][0];
for (int i = 0 ; i < 120 ; i++){
p[i] = i;
}
printf("arr_start = %d, end = %d\n", arr[0][0][0][0][0], arr[4][3][2][1][0]);
return 0;
}
You can test the code here.
Update:
As is mentioned in the comments, using typedef here forces the array to be static sized except the top dimension.
The use of typedef here is only to make the pointer-to-array syntax a little cleaner.
However, with VLA enabled, int (*arr)[n][o][p][q] = malloc(m*sizeof(*arr)); should still work and allow you to specify dynamic size on each dimension.
With dynamic allocation, using malloc:
int** x;
x = malloc(dimension1_max * sizeof(int*));
for (int i = 0; i < dimension1_max; i++) {
x[i] = malloc(dimension2_max * sizeof(int));
}
[...]
for (int i = 0; i < dimension1_max; i++) {
free(x[i]);
}
free(x);
This allocates an 2D array of size dimension1_max * dimension2_max. So, for example, if you want a 640*480 array (f.e. pixels of an image), use dimension1_max = 640, dimension2_max = 480. You can then access the array using x[d1][d2] where d1 = 0..639, d2 = 0..479.
But a search on SO or Google also reveals other possibilities, for example in this SO question
Note that your array won't allocate a contiguous region of memory (640*480 bytes) in that case which could give problems with functions that assume this. So to get the array satisfy the condition, replace the malloc block above with this:
int** x;
int* temp;
x = malloc(dimension1_max * sizeof(int*));
temp = malloc(dimension1_max * dimension2_max * sizeof(int));
for (int i = 0; i < dimension1_max; i++) {
x[i] = temp + (i * dimension2_max);
}
[...]
free(temp);
free(x);
on similar way you can build dynamically 5d array
If I understand your question, that you have a current 5D array, and you need to allocate storage for, and make a copy of that array, and then you wish to access the values in a sequential manner. As others have noted, the approach is to use a pointer to a 4D array to allocate a block of memory dim1 * sizeof 4D to hold your existing array. (you can think about is as allocating for dim1 rows of what makes up your 5D array). You can then simply copy the existing array, (using memcpy or the like) then and assign a pointer to the first element for sequential access.
The benefit is you allocate a single block to hold a copy of your existing array. This will require only a single free when you are done making use of the copy.
This does not work with fake (pointer to pointer to pointer... collections of memory)
Below is a short example of creating a dim1 pointers to what makes up the remaining 4d of your existing array (in a single block allocation) where all but your dim1 dimensions are known at compile time. The existing 5D array a is copied to a new block of memory assigned to b. An integer pointer 'p' is then assigned the beginning address of b. The values of b are accessed sequentially through pointer p.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main (void) {
int a[2][2][2][2][2] = { { { {{1,2}, {3,4}}, /* 5D Array */
{{5,6}, {7,8}} },
{ {{1,2}, {3,4}},
{{5,6}, {7,8}} } },
{ { {{1,2}, {3,4}},
{{5,6}, {7,8}} },
{ {{1,2}, {3,4}},
{{5,6}, {7,8}} } } };
/* ptr to 5D, ptr to int* */
int (*b)[2][2][2][2] = NULL, *p = NULL;
/* allocate block to hold a */
b = malloc (sizeof a/sizeof *a * sizeof *b);
memcpy (b, a, sizeof a/sizeof *a * sizeof *b); /* copy a to b */
p = ****b; /* assign address of first element */
printf ("\nb:\n"); /* ouput using sequential access */
for (int i = 0; i < (int)(sizeof a/sizeof *****a); i++)
printf (" *(p + %2d) : %d\n", i, p[i]);
free (b); /* single free is all that is required */
return 0;
}
Example Use/Output
$ ./bin/arr5dstatic1
b:
*(p + 0) : 1
*(p + 1) : 2
*(p + 2) : 3
*(p + 3) : 4
*(p + 4) : 5
*(p + 5) : 6
*(p + 6) : 7
*(p + 7) : 8
*(p + 8) : 1
*(p + 9) : 2
*(p + 10) : 3
*(p + 11) : 4
*(p + 12) : 5
*(p + 13) : 6
*(p + 14) : 7
*(p + 15) : 8
*(p + 16) : 1
*(p + 17) : 2
*(p + 18) : 3
*(p + 19) : 4
*(p + 20) : 5
*(p + 21) : 6
*(p + 22) : 7
*(p + 23) : 8
*(p + 24) : 1
*(p + 25) : 2
*(p + 26) : 3
*(p + 27) : 4
*(p + 28) : 5
*(p + 29) : 6
*(p + 30) : 7
*(p + 31) : 8
There is good reason that the rest of the comments and answers suggest you find some way other than using a 5D array setup. It would be worth while to investigate if you can modify whatever is producing the data you capture in your original 5D array to output the data in some other format.

Array that points to another array

I'm new to C.
Create an array which holds at every index a pointer to another array of dynamic size.
int main()
{
unsigned int i , j;
int* array1[2];
int a1[] = {1,2,3};
int a2[] = {2,3};
array1[0] = a1;
array1[1] = a2;
for (i=0 ; i < 2; i++) {
printf(" the value of array1[%d] = %d" , i , *array1[i]);
}
return 1;
}
the value of array1[0] = 1
the value of array1[1] = 2
Only first elements are getting printed . How to print the whole array the index points to. What thing i'm missing.
EDITED ::
I now understand the use but similarly doing it directly , causing an array.
`unsigned int* c[3];
c[0] = {0, 5, 4, 7}; // This Line Err`
c[1] = {0, 5, 4, 3, 2, 6, 7};
c[2] = {0, 5, 4, 3, 2};
Causing an error : file try.c line xx function main: syntax error before `{'
Why ??
Thanks
As you know, array1[0] holds a pointer to the first element of a1 array; to print all elements of a1 array, you should iterate over it, something like this:
for (int i = 0; i < 2; i++){
printf(" the value of a1[%d] = %d", i, *(array1[0] + i);
}
An array is decayed to a pointer in C, in particular when passing it as argument (or storing it in a pointer).
What you are missing is that at runtime, the actual size of the array is not kept (and sizeof is a compile-time operator, replaced by the compiler by a constant - except for VLAs).
You might wish to keep the array size and its content together. Using a struct with a last flexible array member is a cute way to do that:
struct vect_st { unsigned size; int flexarr[]; };
struct vect_st* arr1[2];
Such structures need to be heap allocated (because you know their real size only at runtime):
arr1[0] = malloc(sizeof(struct (vect_st) + 2*sizeof(int));
if (!arr1[0]) {perror("malloc arr1[0]"); exit(EXIT_FAILURE); };
arr1[0]->size = 2;
arr1[0]->flexarr[0] = 4;
arr1[0]->flexarr[1] = 17;
arr1[1] = malloc(sizeof(struct (vect_st) + 3*sizeof(int));
if (!arr1[1]) {perror("malloc arr1[1]"); exit(EXIT_FAILURE); };
arr1[1]->size = 3;
arr1[1]->flexarr[0] = 5;
arr1[1]->flexarr[1] = 6;
arr1[1]->flexarr[2] = 7;
OF course, you should release the memory when you don't need it, so you'll probably end your main with code like
free(arr1[0]), arr1[0] = NULL;
free(arr1[1]), arr1[1] = NULL;
Beware of memory leaks, buffer overflows and other undefined behavior. So compile your code with all warnings & debug info (gcc -Wall -Wextra -g) and use valgrind and the gdb debugger.
Notice also that you should usually not declare non-small arrays (or aggregates) as local data (e.g. some local int biglocarr[1000000]; inside your main or some other function), since the call stack is limited in size (typically to a few megabytes, so no more than a few hundred bytes per call frame). Read about stack overflows and avoid them.
You are using *array1[i] , here " * " means pointer and value at array1[i] and i is 0 in first case, so it is pointing to a1 base, i.e. 1 and so on..

Can anyone help me debug this 2D array?

I am trying to increase the size of my 2D array and hm is a struct that contains the x length of the array. I am using value -99999991 to indicate the end of the array.
Is this the correct way to do it?
hm->value = realloc(hm->value,(hm->x+1)*sizeof(int));
hm->value[hm->x] = malloc(sizeof(int));
hm->value[hm->x][0] = -999999991;
hm->value[hm->x-1] = realloc(hm->value[hm->x-1],2*sizeof(int));
hm->value[hm->x-1][1] = -999999991;
hm->value[hm->x-1][0] = value;
You don't have a 2D array if it can be resized, you have a pointer to a pointer to an int.
An array:
int A[n][m];
Accessing the array: A[2][3] = 4; // Equivalent to *(A + 2*m + 3)
A variable sized 2D "array":
int **A;
A = malloc(n*m*sizeof(int));
A[2][3] = 4; // Equivalent to *A + 2*??? + 3)
The compiler doesn't know if your array is one dimensional, or if it is two dimensional then what the size of the two dimensions are. It can't calculate this any more.
Also, realloc can't put the data in the right place. Consider a 2x2 2D array going to a 2x3 2D array:
int **A = {{0,1}, {2,3}}; // for berevity - this isn't valid C!
// stored in memory as [0,1,2,3]
A = realloc(A, 2*3* sizeof(int));
New array stored in memory is [0,1, , 2, 3, ]; This required copying the data.
There are two decent solutions (though they aren't pretty):
1) Treat your 2D array as a list of 1D arrays
int **A;
A = malloc(m*sizeof(void *));
for (i = 0; i < m; ++i) {
A[i] = malloc (n*sizeof(int);
}
(now realloc should work on both of these arrays, but accessing elements will require two pointer dereferences rather than pointer arithmetic)
2) if one of the dimensions of the array is fixed then we can use a 2D array in memory and realloc it as required.
#define M 16
int **A;
A = malloc(M*n*sizeof(int)); // realloc also works
// access an element:
*(A + 3*M + 2) = 4; // (3*M is compile time constant)
In this second example we always grow at the end of our 2D array (so my example of going from 2x2 to 2x3 is illegal - the second 2 is a fixed length).

Resources