A simple question about specifying / specifying an array of C

In higher level languages, I could do something similar to this C example, and that would be nice. However, when I compile this example, it complains bitterly. How can I assign new arrays to a declared array?

int values[3];

if(1)
   values = {1,2,3};

printf("%i", values[0]);

Thanks.

+5
source share
9 answers

you can declare a static array with data to initialize:

static int initvalues[3] = {1,2,3};
if(1)
    memmove(values,initvalues,sizeof(values));
+1
source

You can only perform multiple array assignments when declaring an array:

int values[3] = {1,2,3};

After the announcement, you will have to assign each value individually, i.e.

if (1) 
{
  values[0] = 1;
  values[1] = 2;
  values[2] = 3;
}

, , .

if (1)
{
  for (i = 0 ; i < 3 ; i++)
  { 
    values[i] = i+1;
  }
}
+11

C99, , :

memcpy(values, (int[3]){1, 2, 3}, sizeof(int[3]));

int* values = (int[3]){1, 2, 3};
+6
 //compile time initialization
 int values[3] = {1,2,3};

//run time assignment
 value[0] = 1;
 value[1] = 2;
 value[2] = 3;
+2
#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;
}
+1

memcpy, . - .i i: , , .

typedef struct {
    int i[3];
} inta;

int main()
{
    inta d = {i:{1, 2, 3}};

    if (1)
        d = (inta){i:{4, 5, 6}};

    printf("%d %d %d\n", d.i[0], d.i[1], d.i[2]);

    return 0;
}
0

gcc -O3 ( ), memcpy .

template <typename Array>
struct inner
{
    Array x;
};


template <typename Array>
void assign(Array& lhs, const Array& rhs)
{
    inner<Array>& l( (inner<Array>&)(lhs));
    const inner<Array>& r( (inner<Array>&)(rhs));
    l = r;
}

int main()
{
    int x[100];
    int y[100];

    assign(x, y);
}
0

...:)

char S[16]="";
strncpy(S,"Zoodlewurdle...",sizeof(S)-1);

, , S [8] S [32], , .

OpenBSD strlcpy, , , , strncpy , , .

, ="" 0 , sizeof(S)-1 , , strncpy, 0 , , . ANSI C, .

0
source

I would post this as a comment, but I don't have enough reputation. Another (possibly dirty) way to initialize an array is to wrap it in a structure.

#include <stdio.h>

struct wrapper { int array[3]; };

int main(){
    struct wrapper a;
    struct wrapper b = {{1, 2, 3}};

    a = b;

    printf("%i %i %i", a.array[0], a.array[1], a.array[2]);

    return 0;
}
0
source

All Articles