Sum of two arrays using pointers in C - c

I am trying to create a program in C that calculates the sum of two int arrays using pointers.
Here is an example of what I want to do:
int a[] = {1,2,3,4}
int b[] = {1,2,3,4,5,6}
int c[] = sumArrays(a,b,4,6)
Output : c = {2,4,6,8,5,6}
The problem is my output is different, it shows:
Output : c = {2,4,6,8}
Any idea what did I do wrong and how to correct it ?
Here is my code :
#include <stdio.h>
#include <stdlib.h>
int* sumArrays(int *arr1, int *arr2, int dim1,int dim2)
{
int *ret = NULL;
if(dim1<dim2) ret = (int*) malloc(dim2*sizeof(int));
else ret = (int*) malloc(dim1*sizeof(int));
if(ret)
{
if(dim1<dim2) {
int i = 0;
for (i = 0;i < dim1;i++) {
ret[i] = arr1[i] + arr2[i];
}
for (i = dim1; i < dim2;i++) {
ret[i]=arr2[i];
}
} else {
int i = 0;
for (i = 0;i < dim2;i++) {
ret[i] = arr1[i] + arr2[i];
}
for (i = dim2; i < dim1;i++) {
ret[i]=arr1[i];
}
}
}
return ret;
}
int main()
{
int *a[] = {1,2,3,4};
int *b[] = {1,2,3,4,5,6};
int *c = sumArrays(a,b,4,6);
printf("c = ");
int i;
for (i = 0; i < sizeof(c); i++) {
printf("%d,",c[i]);
}
}

Sizeof c will always return 4 for 32-bit system and 8 for 64-bit, because c is a pointer to int.
So to print the result array you should write:
for (i = 0; i < 6; i++) {

You have problem about using pointers.
int *a[] = {1,2,3,4}; // a is an array of pointers to integers.
int *b[] = {1,2,3,4,5,6}; // b is an array of pointers to integers.
By doing this, you are declaring array of pointers to integers. So, it most likely causes compiler warning or error depending on your compile settings like, initialization makes pointer from integer without a cast. When you are passing the actual arguments to formal parameters, it causes same warning as well. Your main should be like this,
int main()
{
int a[] = {1,2,3,4};
int b[] = {1,2,3,4,5,6};
int sizeA = sizeof(a) / sizeof(*a);
int sizeB = sizeof(b) / sizeof(*b);
int *c = sumArrays(a,b,sizeA,sizeB);
printf("c = ");
int i;
for (i = 0; i < (sizeA < sizeB ? sizeB : sizeA); i++) {
printf("%d,",c[i]);
}
}

Related

Split array into dynamic array and return ptr

I have a problem. I have to divide array into dynamic array and return pointer with parameter.
When I try to run this code, I get (interrupted by signal 11: SIGSEGV) this message. I think it is something with my pointers. But I don't even get any warnings, I don't know where to look else.
#include <stdio.h>
#include <stdlib.h>
int splitData(int data[], int size, int splitPlace, int **firstArray);
int main() {
int data[6] = {1, 2, 3, 4, 5, 6};
int size = 6;
int *ptr = NULL;
int n = splitData(data, size, 3, &ptr);
printf("%d", n);
for(int i = 0; i < 3; ++i)
{
printf("[%d]", ptr[i]);
}
return 0;
}
int splitData(int data[], int size, int splitPlace, int **firstArray)
{
*firstArray = (int *)malloc(splitPlace * sizeof(int));
for(int i = 0; i < splitPlace; ++i)
{
*firstArray[i] = data[i];
}
return 0;
}
You have the precedence wrong with *firstArray[i]. You need (*firstArray)[i].
Clearer might be to allocate
int *new_array = malloc(...);
*firstArray = new_array.
Then use new_array in your loop body.

How to access 2 dimensional Array Pointer in a typedef-struct over a function in c

I have Problems with accessing the 2D Array in a typedef from a other function over a pointer, even if i allocate the array in heap!
#include <stdlib.h>
#include <stdio.h>
typedef struct {
int a;
int b;
int **data;
} Image;
Image *createImage(int a, int b) {
Image createImage;
createImage.data = malloc(a * sizeof(int *));
for (int i = 0; i < a; i++) {
createImage.data[i] = malloc(b * sizeof(int));
}
Image *imagePointer = malloc(sizeof(Image));
imagePointer = &createImage;
return imagePointer;
}
int main () {
int a = 70;
int b = 90;
Image *imagePointer = createImage(a, b);
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
imagePointer->data[i][j] = i + j;
}
}
}
I get an error at load Image because i have done something wrong with accessing the allocated storage. What should i change?
Jonathan
Instead of returning a pointer to Image return the local variable itself and it works. Also variable name and function name should not be same createImage it creates confusion sometimes.
#include <stdlib.h>
typedef struct {
int a;
int b;
int **data;
} Image;
Image createImage(int a, int b) {
Image ci;
ci.data = malloc(a * sizeof(int *));
for (int i = 0; i < a; i++) {
ci.data[i] = malloc(b * sizeof(int));
}
return ci;
}
int loadImage () {
int a = 70;
int b = 90;
Image imagePointer = createImage(a, b);
for (int i = 0; i < a; i++) {
for (int j = 0; j < b; j++) {
imagePointer.data[i][j] = i + j;
}
}
}
int main(int argc, char const *argv[])
{
loadImage();
return 0;
}
It is not 2D array only an array of pointers.
Use size_t for sizes
Use objects not types in sizeof
Always check the result of malloc
I would use flexible array member and array pointers to remove one level of indirection and ease allocation and deallocation (only one malloc/free needed)
typedef struct {
size_t a;
size_t b;
unsigned data[];
} Image;
Image *createImage(const size_t a, const size_t b)
{
Image *imagePointer;
imagePointer = malloc(sizeof(*imagePointer) + a * b * sizeof(imagePointer -> data[0]));
if(imagePointer)
{
imagePointer -> a = a;
imagePointer -> b = b;
}
return imagePointer;
}
int main (void)
{
const size_t a = 70;
const size_t b = 90;
Image *imagePointer = createImage(a, b);
if(imagePointer)
{
unsigned (*image)[imagePointer -> b] = (unsigned (*)[imagePointer -> b])imagePointer -> data;
for (size_t i = 0; i < a; i++)
{
for (size_t j = 0; j < b; j++)
{
image[i][j] = i + j;
}
}
}
}

Function allocate and modify many (more than one) arrays in C [duplicate]

This question already has answers here:
Changing address contained by pointer using function
(5 answers)
Closed 2 years ago.
A C function can modify more than one variable by an illusion of pass-by-reference (a pass-by-value of address as explained by Ely), e.g.:
#include <stdio.h>
void function(int *pa, int *pb) {
*pa *= *pa;
*pb *= *pb;
}
int main(void) {
int a = 1, b = 2;
function(&a, &b);
printf("a = %d\nb = %d\n", a, b);
return 0;
}
which outputs
a = 1
b = 4
It is also possible to modify a whole range of variables by returning a pointer to an array, e.g.:
#include <stdlib.h>
#include <stdio.h>
int *function(int *ptr_size) {
int n = 6; // arbitrary ptr_size
int *array = (int *)malloc(n * sizeof(int));
for (int i = 0; i < n; ++i)
array[i] = i * i;
//
*ptr_size = n;
return array;
}
int main(void) {
int size = 0;
int *array = function(&size);
printf("size = %d\n", size);
for (int i = 0; i < size; ++i)
printf("array[%d] = %d\n", i, array[i]);
free(array);
array = NULL;
return 0;
}
which outputs :
size = 6
array[0] = 0
array[1] = 1
array[2] = 4
array[3] = 9
array[4] = 16
array[5] = 25
But what if I want a function that modify more than one (dynamic allocated) array ?
I tried this
#include <stdlib.h>
#include <stdio.h>
void function(int *array, int *ptr_asize, int *brray, int *ptr_bsize) {
int size = 6;
array = (int *)malloc(size * sizeof(int));
brray = (int *)malloc(size * sizeof(int));
for (int i = 0; i < size; ++i) {
array[i] = i * i;
brray[i] = i * i * i;
}
*ptr_asize = size;
*ptr_bsize = size;
}
int main(void) {
int asize, bsize;
int *array, *brray;
function(array, &asize, brray, &bsize);
// array
printf("asize = %d\n", asize);
for (int i = 0; i < asize; ++i)
printf("array[%d] = %d\n", i, array[i]);
free(array);
array = NULL;
// brray
printf("bsize = %d\n", bsize);
for (int i = 0; i < bsize; ++i)
printf("brray[%d] = %d\n", i, brray[i]);
free(brray);
brray = NULL;
//
return 0;
}
but it makes a segmentation fault.
That is not very surprising, how main would know about how much memory has been allocated to array and brray?
So my question is: is it possible in C that a function allocate and modify more than one array, and those changes remain in main?
PS: A solution would be to allocate a new abrray that contains both array and brray (int **function(...) { ... return abrray; }), but I would like to know if it is possible to a function to modify two (or more) arrays, and that changes remain in main.
Pass a pointer to pointer, like this:
void func(int** array, int** brray, size_t size_a, size_t size_b) {
*array = malloc(size_a * sizeof(int));
*brray = malloc(size_b * sizeof(int));
}
Call it like:
int *arr, *brr;
func(&arr, &brr, 2, 5);
As explained by iTs.SL4y3r, it is possible by passing pointer to pointer.
Here is a minimal working example :
#include <stdlib.h>
#include <stdio.h>
void function(int **array, int *ptr_asize, int **brray, int *ptr_bsize) {
int size = 6;
*array = malloc(size * sizeof(int));
*brray = malloc(size * sizeof(int));
for (int i = 0; i < size; ++i) {
(*array)[i] = i * i;
(*brray)[i] = i * i * i;
}
*ptr_asize = size;
*ptr_bsize = size;
}
int main() {
int asize, bsize;
int *array, *brray;
function(&array, &asize, &brray, &bsize);
// array
printf("asize = %d\n", asize);
for (int i = 0; i < asize; ++i)
printf("array[%d] = %d\n", i, array[i]);
free(array);
array = NULL;
// brray
printf("bsize = %d\n", bsize);
for (int i = 0; i < bsize; ++i)
printf("brray[%d] = %d\n", i, brray[i]);
free(brray);
brray = NULL;
//
return 0;
}
which outputs :
asize = 6
array[0] = 0
array[1] = 1
array[2] = 4
array[3] = 9
array[4] = 16
array[5] = 25
bsize = 6
brray[0] = 0
brray[1] = 1
brray[2] = 8
brray[3] = 27
brray[4] = 64
brray[5] = 125

Print Array Pointer value in Reverse Order

I want to Print Pointer Array value in Reverse
#include <stdio.h>
#define size 5
int main()
{
int a[size] = {1,2,3,4,5};
int i;
int *pa = a;
for(i = size; i >0; i--)
{
printf("a[%d] = %d\n",i,*pa);
pa++;
}
return 0;
}
Output:
a[5] = 1
a[4] = 2
a[3] = 3
a[2] = 4
a[1] = 5
The output I want is:
a[5] = 5
a[4] = 4
a[3] = 3
a[2] = 2
a[1] = 1
replace with this
#include <stdio.h>
#define size 5
int main()
{
int a[size] = {1,2,3,4,5};
int i;
int *pa = (a+size-1);
for(i = size; i >0; i--)
{
printf("a[%d] = %d\n",i,*pa);
pa--;
}
return 0;
}
You're making this too hard. Given a pointer into an array, you can use the indexing operator on it just as you would on the array itself:
int a[size] = {1,2,3,4,5};
int i;
int *pa = a;
for (i = size - 1; i >= 0; i--) {
printf("a[%d] = %d\n", i, pa[i]);
}
Alternatively, if you want to avoid the indexing operator for some reason, then just start your pointer at one past the end ...
*pa = a + size;
... and decrement it as you proceed through the loop:
for (i = size - 1; i >= 0; i--) {
pa--;
printf("a[%d] = %d\n", i, *pa);
}
Do note, by the way, that array indexing in C starts at 0, as the example codes above properly account for.
You don't have to use pointer. A simpler implementation
#include <stdio.h>
#define size 5
int main()
{
int a[size] = {1,2,3,4,5};
for(int i = size-1; i >=0; i--)
printf("a[%d] = %d\n",i,a[i]);
return 0;
}

Return two pointers from a function in c

I know that you can return a pointer to the first element of an array in c by doing:
#include <stdlib.h>
#include <stdio.h>
int *my_func(void);
int main(void)
{
int *a;
int i;
a = my_func();
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, a[i]);
}
free(a);
return 0;
}
int *my_func(void)
{
int *array;
int i;
array = calloc(3, sizeof(int));
for(i = 0; i < 3; i++)
{
array[i] = i;
}
return array;
}
But if I wanted to return two pointers instead of just one, I tried:
#include <stdlib.h>
#include <stdio.h>
int *my_func(int *);
int main(void)
{
int *a;
int *b;
int i;
a = my_func(b);
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, a[i]);
printf("b[%d] = %d\n", i, b[i]);
}
free(a);
free(b);
return 0;
}
int *my_func(int *array2)
{
int *array;
int i;
array = calloc(3, sizeof(int));
array2 = calloc(3, sizeof(int));
for(i = 0; i < 3; i++)
{
array[i] = i;
array2[i] = i;
}
return array;
}
But this seg faults on the printf for b. I ran it through valgrind and it says that there is an invalid read of size 4 at the printf for b, which means I'm doing something screwy with the b pointer. I was just wondering what the best way to "return" a second pointer to an array was in c? I'm asking because I would like to do it this way rather than use a global variable (I'm not opposed to them, as they are useful at times, I just prefer not to use them if possible). The other questions I've seen on this site used statically allocated arrays, but I haven't yet stumbled across a question that was using dynamic allocation. Thanks in advance!
I can think of three (and a half) simple ways to return multiple items of any kind from a C-function. The ways are described below. It looks like a lot of text, but this answer is mostly code, so read on:
Pass in an output argument as you have done, but do it correctly. You have to allocate space for an int * in main() and then pass the pointer to that to my_func.
In main():
a = my_func(&b);
my_func() becomes:
int *my_func(int **array2)
{
int *array;
int i;
array = calloc(3, sizeof(int));
*array2 = calloc(3, sizeof(int));
for(i = 0; i < 3; i++)
{
array[i] = i;
(*array2)[i] = i;
}
return array;
}
Make your function allocate array of two pointers to the int arrays you are trying to allocate. This will require an additional allocation of two int pointers, but may be worth the trouble.
main() then becomes:
int main(void)
{
int **ab;
int i;
ab = my_func(b);
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, ab[0][i]);
printf("b[%d] = %d\n", i, ab[1][i]);
}
free(ab[0]);
free(ab[1]);
free(ab);
return 0;
}
my_func() then becomes:
int **my_func(void)
{
int **arrays;
int i, j;
arrays = calloc(2, sizeof(int *));
arrays[0] = calloc(3, sizeof(int));
arrays[1] = calloc(3, sizeof(int));
for(j = 0; j < 2; j++)
{
for(i = 0; i < 3; i++)
{
arrays[j][i] = i;
}
}
return arrays;
}
Return a structure or structure pointer. You will need to define the structure, and decide whether you want to return the structure itself, a newly allocated pointer to it, or pass it in as a pointer and have my_func() fill it in for you.
The structure definition would look something like this:
struct x
{
int *a;
int *b;
}
You would then rephrase your current functions as one of the following three options:
Direct passing of structure (not recommended for general use):
int main(void)
{
struct x ab;
int i;
ab = my_func();
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, ab.a[i]);
printf("b[%d] = %d\n", i, ab.b[i]);
}
free(ab.a);
free(ab.b);
return 0;
}
struct x my_func(void)
{
struct x ab;
int i;
ab.a = calloc(3, sizeof(int));
ab.b = calloc(3, sizeof(int));
for(i = 0; i < 3; i++)
{
ab.a[i] = i;
ab.b[i] = i;
}
return ab;
}
Return a pointer to a dynamically allocated structure (this is a pretty good option in general):
int main(void)
{
struct x *ab;
int i;
ab = my_func();
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, ab->a[i]);
printf("b[%d] = %d\n", i, ab->b[i]);
}
free(ab->a);
free(ab->b);
free(ab);
return 0;
}
struct x *my_func(void)
{
struct x *ab;
int i;
ab = malloc(sizeof(struct x));
ab->a = calloc(3, sizeof(int));
ab->b = calloc(3, sizeof(int));
for(i = 0; i < 3; i++)
{
ab->a[i] = i;
ab->b[i] = i;
}
return ab;
}
Allocate the structure in main() and fill it in in my_func via a passed-in pointer. This option is often used in a way where my_func would allocate the structure if you pass in a NULL pointer, otherwise it would return whatever you passed in. The version of my_func shown here has no return value for simplicity:
int main(void)
{
struct x ab;
int i;
my_func(&ab);
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, ab.a[i]);
printf("b[%d] = %d\n", i, ab.b[i]);
}
free(ab.a);
free(ab.b);
return 0;
}
void my_func(struct x *ab)
{
int i;
ab->a = calloc(3, sizeof(int));
ab->b = calloc(3, sizeof(int));
for(i = 0; i < 3; i++)
{
ab->a[i] = i;
ab->b[i] = i;
}
return;
}
For all the examples shown here, don't forget to update the declaration of my_func at the top of the file, although I am sure any reasonable compiler will remind you if you forget.
Keep in mind also that these are just three options I pulled out of my brain at a moments notice. While they are likely to cover 99% of any use cases you may come up against any time soon, there are (probably lots of) other options out there.
Function parameters are its local variables. Functions deal with copies of values of the supplied arguments.
You can imagine your function definition and its call the following way
a = my_func(b);
int *my_func( /* int *array2 */ )
{
int *array2 = b;
//...
}
So any changes of the local variable array2 inside the function do not influence on the original argument b.
For such a function definition you have to pass the argument by reference that is the function should be declared like
int *my_func( int **array2 );
^^
There are many ways to implement the function. You could define a structure of two pointers as for example
struct Pair
{
int *a;
int *b;
};
and use it as the return type of the function
struct Pair my_func( void );
Another approach is to pass to the function an array of pointers to the original pointers.
The function can look as it is shown in the demonstrative program.
#include <stdio.h>
#include <stdlib.h>
size_t multiple_alloc( int ** a[], size_t n, size_t m )
{
for ( size_t i = 0; i < n; i++ ) *a[i] = NULL;
size_t k = 0;
for ( ; k < n && ( *a[k] = malloc( m * sizeof( int ) ) ) != NULL; k++ )
{
for ( size_t i = 0; i < m; i++ ) ( *a[k] )[i] = i;
}
return k;
}
#define N 2
#define M 3
int main(void)
{
int *a;
int *b;
multiple_alloc( ( int ** [] ) { &a, &b }, N, M );
if ( a )
{
for ( size_t i = 0; i < M; i++ ) printf( "%d ", a[i] );
putchar( '\n' );
}
if ( b )
{
for ( size_t i = 0; i < M; i++ ) printf( "%d ", b[i] );
putchar( '\n' );
}
free( a );
free( b );
return 0;
}
The program output is
0 1 2
0 1 2
#include <stdlib.h>
#include <stdio.h>
int *my_func(int **);
int main(void)
{
int *a;
int *b;
int i;
b=(int *)malloc(sizeof(int));
a = my_func(&b);
for(i = 0; i < 3; i++)
{
printf("a[%d] = %d\n", i, a[i]);
printf("b[%d] = %d\n", i, b[i]);
}
free(a);
free(b);
return 0;
}
int *my_func(int **array2)
{
int *array;
int i;
array = calloc(3, sizeof(int));
*array2 =calloc(3,sizeof(int));
for(i = 0; i < 3; i++)
{
array[i] = i;
*((*array2)+i)=i;//or (*array2)[i]
}
return array;
}
Pass the pointer by reference. Because its the same logic as, to manipulate an integer block you need to pass a pointer to it. Similarly, to manipulate a pointer, you will have to pass a pointer to it(i.e. pointer to pointer).

Resources