Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C struct problem

Tags:

c

struct

I am trying to learn about structs in C, but i do not understand why i cannot assign the title as i my example:

#include <stdio.h>

struct book_information {
 char title[100];
 int year;
 int page_count;
}my_library;


main()
{

 my_library.title = "Book Title"; // Problem is here, but why?
 my_library.year = 2005;
 my_library.page_count = 944;

 printf("\nTitle: %s\nYear: %d\nPage count: %d\n", my_library.title, my_library.year, my_library.page_count);
 return 0;
}

Error message:

books.c: In function ‘main’:
books.c:13: error: incompatible types when assigning to type ‘char[100]’ from type ‘char *’
like image 390
peter_larsson80 Avatar asked Nov 16 '10 17:11

peter_larsson80


People also ask

What are the disadvantages of structure in C?

Disadvantages of Structure and Union in CStructure is slower because it requires storage space for all the data. If the complexity of an IT project goes beyond the limit, it becomes hard to manage. Change of one data structure in a code necessitates changes at many other places.

What is struct in C with example?

struct structureName { dataType member1; dataType member2; ... }; For example, struct Person { char name[50]; int citNo; float salary; }; Here, a derived type struct Person is defined.

Which type of problem can be solved by structure in C?

We use structures to overcome the drawback of arrays. We already know that arrays in C are bound to store variables that are of similar data types. Creating a structure gives the programmer the provision to declare multiple variables of different data types treated as a single entity.

How does struct work in C?

Structures (also called structs) are a way to group several related variables into one place. Each variable in the structure is known as a member of the structure. Unlike an array, a structure can contain many different data types (int, float, char, etc.).


2 Answers

LHS is an array, RHS is a pointer. You need to use strcpy to put the pointed-to bytes into the array.

strcpy(my_library.title, "Book Title");

Take care that you do not copy source data > 99 bytes long here as you need space for a string-terminating null ('\0') character.

The compiler was trying to tell you what was wrong in some detail:

error: incompatible types when assigning to type ‘char[100]’ from type ‘char *’

Look at your original code again and see if this makes more sense now.

like image 163
Steve Townsend Avatar answered Sep 23 '22 00:09

Steve Townsend


As the message says, the issue is you are trying to assign incompatible types: char* and char[100]. You need to use a function like strncpy to copy the data between the 2

strncpy(my_library.title, "Book Title", sizeof(my_library.title));
like image 45
JaredPar Avatar answered Sep 25 '22 00:09

JaredPar