Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array slicing in C

Tags:

arrays

c

In Python, if I wanted to assign the vector x=(1,2) to the first two elements of y=(0,0,0,0), I would do something like y[:1] = x. Is there an equivalent in C to assign a double x[2]={1.,2.} to the first two elements of an available double y[4] = {0.,0.,0.,0.}? Or will I have to loop?

like image 310
conjectures Avatar asked Dec 31 '14 18:12

conjectures


People also ask

Can you slice an array in C?

Array-slicing is supported in the print and display commands for C, C++, and Fortran. Expression that should evaluate to an array or pointer type. First element to be printed. Defaults to 0.

What do you mean by array slicing?

In computer programming, array slicing is an operation that extracts a subset of elements from an array and packages them as another array, possibly in a different dimension from the original.

What is slicing in C programming?

Overview. The Slicing plug-in produces an output program which is made of a subset of the statements of the analyzed program, in the same order as in the analyzed program. The statements are selected according to a user-provided slicing criterion.

Can we do slicing in C?

Slicing Strings with strsep()The strtok() function is the traditional C library routine used to slice up a string. It has its limitations, however, so a more recent function was included in the library on some compilers to replace it: strsep().


1 Answers

Just try this

#include <string.h>
#include <stdio.h>

int main()
{
    double x[2] = {1., 2.};
    double y[4] = {0., 0., 0., 0.};

    memcpy(y, x, 2 * sizeof(*x));
              /* ^ 2 elements of size -> sizeof(double) */

    return 0;
}

instead of writing sizeof(double) which is ok, i did sizeof(*x) because if I change the type of x I wouldn't need to fix the memcpy, but i would also have to change the type of y in that case.

like image 54
Iharob Al Asimi Avatar answered Sep 28 '22 03:09

Iharob Al Asimi