In higher level languages I would be able something similar to this example in C and it would be fine. However, when I compile this C example it complains bitterly. How can I assign new arrays to the array I declared?
int values[3];
if(1)
values = {1,2,3};
printf("%i", values[0]);
Thanks.
To create an array, define the data type (like int ) and specify the name of the array followed by square brackets []. To insert values to it, use a comma-separated list, inside curly braces: int myNumbers[] = {25, 50, 75, 100}; We have now created a variable that holds an array of four integers.
You can do array assignment within structs: struct data { int arr[10]; }; struct data x = {/* blah */}; struct data y; y = x; But you can't do it directly with arrays.
Array declaration syntax is very simple. The syntax is the same as for a normal variable declaration except the variable name should be followed by subscripts to specify the size of each dimension of the array. The general form for an array declaration would be: VariableType varName[dim1, dim2, ...
You can only do multiple assignment of the array, when you declare the array:
int values[3] = {1,2,3};
After declaration, you'll have to assign each value individually, i.e.
if (1)
{
values[0] = 1;
values[1] = 2;
values[2] = 3;
}
Or you could use a loop, depending on what values you want to use.
if (1)
{
for (i = 0 ; i < 3 ; i++)
{
values[i] = i+1;
}
}
In C99, using compound literals, you could do:
memcpy(values, (int[3]){1, 2, 3}, sizeof(int[3]));
or
int* values = (int[3]){1, 2, 3};
//compile time initialization
int values[3] = {1,2,3};
//run time assignment
value[0] = 1;
value[1] = 2;
value[2] = 3;
you can declare static array with data to initialize from:
static int initvalues[3] = {1,2,3};
…
if(1)
memmove(values,initvalues,sizeof(values));
#include<stdio.h>
#include<stdlib.h>
#include<stdarg.h>
int *setarray(int *ar,char *str)
{
int offset,n,i=0;
while (sscanf(str, " %d%n", &n, &offset)==1)
{
ar[i]=n;
str+=offset;
i+=1;
}
return ar;
}
int *setarray2(int *ar,int num,...)
{
va_list valist;
int i;
va_start(valist, num);
for (i = 0; i < num; i++)
ar[i] = va_arg(valist, int);
va_end(valist);
return ar;
}
int main()
{
int *size=malloc(3*sizeof(int*)),i;
setarray(size,"1 2 3");
for(i=0;i<3;i++)
printf("%d\n",size[i]);
setarray2(size,3 ,4,5,6);
for(i=0;i<3;i++)
printf("%d\n",size[i]);
return 0;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With