0

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?

Edited by hg_fs2002

3
Contributors
4
Replies
20
Views
4 Years
Discussion Span
Last Post by rubberman
0

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.

0

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?

0

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?

0

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));
}
This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.