1

I am having a problem operating with a char array. My idea was to use scanf to store input in a char array and then store the contents of that array inside a struct.

Here is the code which may be easier for you to understand:

struct ListaCategoria {
    int ident;
    char data[MAX];
    struct ListaCategoria* next;
};

struct ListaCategoria* headCat;

void inserirCat(){
    int x;
    char arr[MAX];
    printf("Identificacao : ");
    scanf("%d", &x);
    printf("Designacao : ");
    scanf("%c[^\n]", &arr);
    struct ListaCategoria* temp = (struct ListaCategoria*) malloc(sizeof(struct ListaCategoria));

    (*temp).ident = x;
    (*temp).data = arr; //this is the line that's giving some trouble can someone explain me why?
}
bcsb1001
  • 2,834
  • 3
  • 24
  • 35
Rui Vieira
  • 61
  • 1
  • 1
  • 10

1 Answers1

1

To scan in data into a C-"string" use %s, %c is for exactly one char only.

Also as for scanning into an array you would pass the array and with this it will decay to the address of it's 1st element you do not need to use the address-of operator on it.

scanf("%s[^\n]", arr);

Additionally you should tell scanf() to not overflow the buffer passed by specifying its size (assuming #define MAX (42)):

scanf("%41s[^\n]", arr); /* specify one less, as C-"string" always carry 
                            and additional char, the so called `0`-terminator 
                            marking the end of the string. */

With this line

(*temp).data = arr;

you are trying to assign an array to an array. This is not possible in C.

In general for copying the content of an array other approaches need to be taken:

  • loop and assign each element's value separately
  • copy the source memory's content to the destination memory

For the latter case and if

  • both arrays are char-arrays
  • the source array is a C-"string"

the most common approach is to use the function strcpy():

strcpy((*temp).data, arr);

This function not copies all of the array's content, but only the part in use, namely until the 0-terminator, marking the end of the string of detected.

alk
  • 69,737
  • 10
  • 105
  • 255