0

im trying to learn c programming and and im just lost on how i can split my array of ints, size created via malloc in half, and pass each half of the array to a different function each, array created

to create the size i used a size variable, then asked for user input then passed that value into my malloc function.

int* ptr;
ptr =(int*)malloc(size * sizeof(int));
for (int i = 0; i < size; ++i)
{
   printf("enter a number\n");
   scanf("%d", &temp);
   ptr[i] = temp;
}

and then once my array has been created, I need to split it in half and pass it to the functions, but I'm unsure on how to access the array at this stage, as again im still new,

so my ptr variable is that like a location holder, or array name similar to a array like so in java?

int[] pointername = new int[20];

where the pointername is in c my ptr variable? just trying to understand or find my array reference

Hamburger
  • 3
  • 2
  • [dont cast malloc](https://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc) – Barmar Mar 24 '21 at 23:17
  • `ptr` is analogous to `pointername` – Barmar Mar 24 '21 at 23:19
  • 1
    The function needs to take a pointer and size. So to pass the first half, you pass `ptr` and `size/2`. To pass the second half, you pass `ptr + size/2` and `size - size/2`. – Barmar Mar 24 '21 at 23:20

1 Answers1

1

ptr points to a contiguous block of integer objects, and can be indexed as if it were an array. The address of any element can be taken, and that pointer too can be indexed as if it were an array. So:

int* firsthalf = ptr ;
int* secondhalf = &ptr[size/2] ;

Then you can access firsthalf[i], secondhalf[i].

Note that:

size_t firsthalf_size = size / 2 ;
size_t secondhalf_size = size - size / 2 ;

This is important if size is odd, the first half will be the shorter of the two, and there is no bounds checking. If you want to make the first half the longer then:

int* firsthalf = ptr ;
int* secondhalf = &ptr[size - size/2] ;
size_t firsthalf_size = size - size / 2 ;
size_t secondhalf_size = size / 2 ;
Clifford
  • 88,407
  • 13
  • 85
  • 165
  • ah sorry i dont quite understand what you mean by these lines ``` size_t firsthalf_size = size / 2 ; size_t secondhalf_size = size - size / 2 ; ``` but i do see what you mean by it being important if its odd as i have reached the stage where i am printing out the outputs and its omiting a number if its odd, but again i dont understand what you mean by those lines – Hamburger Mar 25 '21 at 00:26
  • OH NVM after a bit of googling since i havent seen size_t before, i just passed them in my for loops in place of the size such as for (int i = 0; i – Hamburger Mar 25 '21 at 00:33
  • @Hamburger sIze_t is a type alias for the length of an array. It is an unsigned integer. That is just me being fastidious about type. You might use int and generally nothing bad will happen. – Clifford Mar 25 '21 at 07:37