split an array into several parts

Asked

Viewed 3,217 times

1

Is there any way to access only a specific part of an array in c? For example, in python it is possible for me to access a specific part of an array.

array[10] = 1,2,3,4,5,6,7,8,9,10
array[4:8] = 5,6,7,8

I wanted to know if you have something similar in c, I need to pass a specific part of an array to a function. My array is a string array. So:

char** string = = malloc(1000 * sizeof(char *));

I wanted to move to a function the matrix from position 0 to position 500.

  • 1

    What is this function like? It takes the size of the array as argument?

  • It is a function of MPI, the Broadcast function, wanted to send a piece of the matrix for each process.

2 answers

3


You can see an array of C as being a mere pointer to the first element. It doesn’t even store the information of how many elements there are. Thus, usually functions that take an array as argument also take the size of the array as a second argument. Example:

int* array = malloc(1000 * sizeof(int));

func(array, 1000);

This means that you can play with the arguments passed to the function. For example, to get only the first 500 items:

func(array, 500);

And the last 500:

func(array+500, 500);

Just be careful not to pass more than the array has. Don’t allow the function to read data out of the array memory.

0

As in C, the variable only stores the beginning of the vector. You can play with the function mempcy and copy a memory block

#define NUM 1000

char** string = malloc(NUM * sizeof(char *));
char** parte1 = malloc((int)(NUM/2) * sizeof(char *));
char** parte2 = malloc((int)(NUM/2) * sizeof(char *));

memcpy(parte1, string, (int)(NUM/2) * sizeof(int)); 
memcpy(parte2, &string + (int)(NUM/2), (int)(NUM/2) * sizeof(int));

So you will have two new strings. One containing the first 500 and the other the last 500 elements of the original string.

  • What happens if NUM is odd?

  • Hi vhbsouza! There is a little typing error in the answer: it is written mempcy in the first paragraph. Now, about the comment of Guilherme Bernal, really if NUM is odd, you will have serious problems: it will be missing copy 1 element. Remembering that 9 / 2, with integers, gives 4! So, you would only copy 8 elements. You need to do something like this: no size of the first memcpy, utilise NUM/2, already in the size of the second, use NUM-(NUM/2) :) Also, in the second memcpy, may withdraw the operator & of the variable string. And in both memcpy, the sizeof(int) should be sizeof(char*).

  • in fact, @carlosrafaelgn. Obg for the observations. I sketched quickly and forgot to think about the odd NUM case and about the sizeof I did on my pc using whole from there when I pasted the code here I used string to make his case. Sheer lack of attention.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.