Gabo Eremita
Gabo Eremita

Reputation: 13

Trying to pass a char[] to another in C

Ok, I have no idea what to do here:

struct
{
       char nombre[30];
       int codigo;     
 }productos[10];

int z = 0;
char tempchar[30]; 

for (z=0; z<9; z++)  {
           if (productos[z].codigo>productos[z+1].codigo) {           
              tempchar = productos[z].nombre;
              productos[z].nombre = productos[z+1].nombre;                  
              productos[z+1].nombre = tempchar;
           }
     }

I get the following error message: ISO C++ forbids assignment of arrays

There's obviously more code but I just included what it has to do with the error. I just want to sort the names of the product by code. So, what can I do here?

Upvotes: 0

Views: 103

Answers (4)

huangtaya
huangtaya

Reputation: 1

there is another way

struct
{
  char *nombre = (char*)malloc(sizeof(char) * 30);
  int codigo;     
}productos[10];
int z = 0;
char *tempchar = (char*)malloc(sizeof(char) * 30);

for (z=0; z<9; z++)  {
  if (productos[z].codigo>productos[z+1].codigo) {           
          tempchar = productos[z].nombre;
          productos[z].nombre = productos[z+1].nombre;                  
          productos[z+1].nombre = tempchar;
       }
 }

Upvotes: 0

youdontneedtothankme
youdontneedtothankme

Reputation: 672

When sorting an array of structs, you typically want to swap the whole struct, not just a single member. Luckily for you, the assignement operator works on structs, even if they contain arrays. So your sort algorithmus will be less buggy if you do this:

temp = productos[z]; 
productos[z] = productos[z+1];
productos[z+1] = temp;

(how to declare temp is left as exercise for the reader)

Alternatively, if you are allowed to use c++, you can do

std::swap(productos[z],productos[z+1]);

Just remember, your sort algorithmus is still buggy. You should lookup "bubblesort" for a dead easy sort algorithmus you can implement. Or even better, if this is not an exercise, use an existing implementation like qsort or std::sort

Upvotes: 0

Is it in C or in C++?

In C you should use strcmp(3) to compare strings and strcpy(3) to copy them. Be very careful of buffer overflow (perhaps use strncmp and strncpy etc...). Ensure that all your strings are null-terminated. Use qsort(3) for sorting.

In C++, you should use std::string which knows about <; you can then use std::sort to sort them. And if you use ordered containers like std::set or std::map they will be ordered by construction.

Upvotes: 4

simonc
simonc

Reputation: 42175

Use strcpy to assign char arrays

strcpy(tempchar, productos[z].nombre);
strcpy(productos[z].nombre, productos[z+1].nombre);
strcpy(productos[z+1].nombre, tempchar);

Upvotes: 2

Related Questions