-5

I am confused about why I am getting an error while initializing a structure variable. I have found a few related threads on Stack Overflow, but they did not solve my problem. Can anyone explain what is causing the problem?

 //I have used Dev-C++ compiler
 //Getting an error 'b1' undeclared
  struct book
 {
           char name ;
            float price ;
            int pages ;
  };

   struct book b1;     

  int main()
 {

    /* First i have tried following way to initialize the structure variable,
    but compiler throws the error 

    b1 = {"John", 12.00, 18};

    */

     //I have tried to initialize individually ....but still getting error...?

     b1.name = "John";
     b1.price = 12.3;
     b1.pages = 23;

     printf ( "\n%s %f %d", b1.name, b1.price, b1.pages );


     system("pause");
     return 0;
  }
4

4 回答 4

0

The problem is that you have declared name as a char. That means name will hold only a single char, not an entire string.

You can statically allocate name as an array of char:

char name [25]  // or whatever length you think is appropriate
                // remember to leave room for the NUL character

Then you will need to use strcpy() to copy the actual name into the structure.

Alternatively, you can declare name as a pointer to char:

char* name;

In this case, you can set the pointer to a string literal:

name = "John";

But in most real life situations, this is not an option, as you will be reading the name in from a file or standard input. So you will need to read it into a buffer, set the pointer to dynamically allocated memory on the heap (the string length of the buffer + 1 for the NUL), and then use strcpy().

于 2013-08-13T04:10:09.970 回答
0

问题

  1. 只有一个字节的内存可用于name字段。使用喜欢char name[100]

  2. 使用strcpy()代替b1.name = "John"

于 2013-08-13T03:47:08.073 回答
0

您显然想要一个字符串变量struct,但您将其声明为char name;单个字符)。

相反,请使用char指针 ( const char *name) 或char数组 ( char name[100])。在后一种情况下,您将不得不使用strcpy(b1.name, "John").

于 2013-08-13T03:50:30.400 回答
0

您必须对代码进行一些调整才能使其正常工作。

char name;  // only one byte is allocated.

定义 char 数组以在 C 中存储字符串。

char name[20]; //stores 20 characters
char *name; //Pointer variable. string size can vary at runtime.

为结构创建对象后,您只能使用该对象提供数据。

(即) object.element=something;

b1 = {"John", 12.00, 18}; // Not possible

只有在定义对象时才可以进行上述初始化。

struct book b1={"John", 12.00, 18}; //Possible

如果 char *name在 struct 中定义,您可以执行以下操作。

struct book b1;
b1.name="John";   // Possible
b1.price=12.00;   // Possible
b1.pages=18;      // Possible

如果您使用 char 数组char name[20]那么您可以执行以下操作。

struct book b1;
strcpy(b1.name,"John");  // Possible
b1.price=12.00;     // Possible
b1.pages=18;       // Possible
于 2013-08-13T04:18:12.663 回答