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!

errorline1
  • 350
  • 1
  • 6
  • 18
  • You didn't post the `strArray` declaration, and you can't assign to arrays. And [Don't cast the result of `malloc()`](http://stackoverflow.com/questions/605845/do-i-cast-the-result-of-malloc). – Iharob Al Asimi Mar 08 '15 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. – JovanMali Mar 09 '15 at 00:01

2 Answers2

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]);
Iharob Al Asimi
  • 52,653
  • 6
  • 59
  • 97
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.

M.M
  • 138,810
  • 21
  • 208
  • 365