Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assign multiple values to array in C

Is there any way to do this in a condensed form?

GLfloat coordinates[8]; ... coordinates[0] = 1.0f; coordinates[1] = 0.0f; coordinates[2] = 1.0f; coordinates[3] = 1.0f; coordinates[4] = 0.0f; coordinates[5] = 1.0f; coordinates[6] = 0.0f; coordinates[7] = 0.0f; return coordinates; 

Something like coordinates = {1.0f, ...};?

like image 879
UnstableFractal Avatar asked Aug 20 '10 22:08

UnstableFractal


People also ask

Can you assign multiple variables at once in C?

If your variables are the same type, you can define multiple variables in one declaration statement. For example: int age, reach; In this example, two variables called age and reach would be defined as integers.

How do you assign values to an array?

Assigning values to an element in an array is similar to assigning values to scalar variables. Simply reference an individual element of an array using the array name and the index inside parentheses, then use the assignment operator (=) followed by a value.

How do you store multiple data in an array?

No, we cannot store multiple datatype in an Array, we can store similar datatype only in an Array.


2 Answers

If you really to assign values (as opposed to initialize), you can do it like this:

 GLfloat coordinates[8];   static const GLfloat coordinates_defaults[8] = {1.0f, 0.0f, 1.0f ....};  ...   memcpy(coordinates, coordinates_defaults, sizeof(coordinates_defaults));   return coordinates;  
like image 87
James Curran Avatar answered Oct 12 '22 13:10

James Curran


Although in your case, just plain initialization will do, there's a trick to wrap the array into a struct (which can be initialized after declaration).

For example:

struct foo {   GLfloat arr[10]; }; ... struct foo foo; foo = (struct foo) { .arr = {1.0, ... } }; 
like image 44
domen Avatar answered Oct 12 '22 11:10

domen