split an array into multiple parts

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 there is 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 the array from position 0 to position 500 to a function.

    
asked by anonymous 20.05.2014 / 04:03

2 answers

3

You can see an array of C as being a mere pointer to the first element. It does not even keep track of how many elements there are. Thus, generally the functions that take an array as an argument also take the size of the array as a second argument. Example:

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

func(array, 1000);

This means you can play around with 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. Do not allow the function to read data out of array memory.

    
20.05.2014 / 04:23
0

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

#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.

    
20.05.2014 / 05:06