0

I'm having trouble trying to assign a md array into a struct md array. Basically:

typdef struct {
  int num;
  char array[30][80];
} Vars;

then in main I did some parsing to make an array of strings, which is aclled strArray and is also [30][80]. However, when I try to do this

char strArray[30][80] = {"example", "text"};
Vars *vars = (Vars *) malloc(sizeof(Vars);
vars->array = strArray;

I keep getting an error

error: incompatible types when assigning to type ‘char[30][80]’ from type ‘char (*)[80]’

I've tried to do it even string by string in a for loop, but keep getting errors. Any ideas? Thanks!

2
  • You didn't post the strArray declaration, and you can't assign to arrays. And Don't cast the result of malloc(). Commented Mar 8, 2015 at 23:57
  • You can't assign dynamic memory to a pointer of statically allocated array. Also you're missing a bracket after sizeof(Vars) when you allocate. You should also give us a declaration of strArray. Commented Mar 9, 2015 at 0:01

2 Answers 2

2

I don't know what you are trying to do, but you can't assign to arrays.

What you probably want is

#include <string.h>

size_t i;

for (i = 0 ; i < 80 ; i++)
    strcpy(vars->array[i], strArray[i]);
Sign up to request clarification or add additional context in comments.

Comments

0

Vars vars = (Vars *) malloc(sizeof(Vars); doesn't even compile. Hopefully you meant something like:

Vars *vars = malloc( sizeof *vars );

Now, arrays cannot be assigned by value. To make a copy of the array you will have to use functions which can cope with arrays. One way would be:

STATIC_ASSERT( sizeof vars->array == sizeof strArray );
memcpy(&vars->array, &strArray, sizeof strArray);

If you do not really want to copy the data then consider having Vars contain a pointer instead of an array; then you can just make that point at strArray. The type would be char (*array)[80];.

Another option would be for strArray to actually be a Vars struct (even if you don't use num); then you can just use structure assignment to do the copying.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.