I have this code:

typedef struct {
  int a
} array[1];

int main (array var)
{
  if ((var->a) == 0)
    return 0;
}

and I want to copy var to a new variable. It seems it should be something like

typedef struct {
  int a
} array[1];

int main (array var)
{
  array newvar = var;
  if ((newvar->a) == 0)
    return 0;
}

But when I compile this program I get this error: invalid initializer. So, if array is not the correct type what is the correct type for var when I want to assign it to a new variable?

Arrays cannot be copied, but if you really want to do it with the assignment operator, you can wrap the array itself in a structure

#include<stdio.h>

typedef struct {
    int data[5];
} array;

void foo(array b)
{
    int i;

    for (i = 0; i < 5; i++) {
        printf("%d\n", b.data[i]);
    }
}

int main(void)
{
    array a = {1, 2, 3, 4, 5};

    foo(a);

    return 0;
}

Though the first question that pops up in reading your sample pseudocode is why do you need an array if it's an array of size 1? Why not just use a regular variable of the structure? Those are assignable.

Actually that's not my code, it is an example of what is in an open source C library (I just changed the variable names and made it simple) which I should extract 'var' there. So, you mean there is not anyway to extract var as it is in my code? Right?

Actually that's not my code

It's not code at all, given that it's illegal C.

So, you mean there is not anyway to extract var as it is in my code?

I don't know what you mean by "extract". Can you be more specific, or use conventional terminology?

This might work in C++, but not C. To copy array data like this from one variable to another in C, you would either do a member-by-member assignment, or alternatively a memcpy() operation. Example:

void copyarray(array var1)
{
    array var2;
    memcpy((void*)&var2, (const void*)&var1, sizeof(array));
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.