返回结构指针的字符串打印随机结果[重复]

问题描述 投票:-4回答:2

这个问题在这里已有答案:

我正在尝试从链表中打印字符串...由于某种原因,它输出随机符号和字符。

这是我的代码:

int main(){

char c;
int titleCount;
int authorCount;
char bookTitle[35];
char author[35];



/* Create Struct */
typedef struct bookData{
char bookTitle[35];
char author[35];
int book_stock;
float retail_price;
int wholesale_purchased;
int customer_purchased;
struct bookData *book;
}new_book;

/*Create Node */

typedef struct Node{
new_book books;
struct Node *next;
}node_t;




/* We are GUARANTEED at least 1 input value, so go ahead and initialize 
the 
head */

node_t *head = NULL; /*Initalize head to NULL since it is empty */
head = malloc(sizeof(node_t));
if(head == NULL){
printf("allocation failed");
return 0;
}
head -> next = NULL;
/*Memory allocation successful */

/*Might as well populate the head with data from the user */

titleCount = 0;
authorCount = 0;


printf("Enter Title\n");
while(( c = getchar()) != '\n'){
    bookTitle[titleCount++] = c;

}
bookTitle[titleCount] = '\0';

printf("%s", bookTitle);
strcpy((head -> books).bookTitle,bookTitle);

printf("Enter Author\n");
while(( c = getchar()) != '\n'){
    author[authorCount++] = c;
}
author[authorCount] = '\0';
strcpy((head -> books).author, author);


printf("Bookstock #:\n");
scanf("%d", &(head -> books).book_stock);

printf("Enter retail price $:\n");
scanf("%f", &(head -> books).retail_price);

printf("Enter Wholesale purchased quanity:\n");
scanf("%d", &(head  -> books).wholesale_purchased);

printf("Enter quantity sold:\n");
scanf("%d", &(head -> books).customer_purchased);



printf("%c\n", head -> books.bookTitle);

printf("%c\n", head -> books.author);

printf("%d\n", head -> books.book_stock);

printf("%.2f\n", head -> books.retail_price);

printf("%d\n", head -> books.wholesale_purchased);

printf("%d\n", head -> books.customer_purchased);


}

我的输出如下:

Output

我被迫使用char阵列的35所以没有绕过那个。我很肯定指针调用是正确的,因为这似乎是所有答案相关的说法。

谢谢

c struct linked-list nodes
2个回答
0
投票

head->books.bookTitle是一个char数组,并直接将其与另一个数组分配,导致错误

错误:使用数组类型赋值给表达式

以下声明

head -> books.bookTitle = bookTitle;

应该

strcpy(head -> books.bookTitle, bookTitle);

同样head -> books.author = author; - > strcpy((head -> books).author,author);

wholesale_purchased在结构中被声明为int,你使用%f作为格式说明符是错误的,它应该是

scanf("%d", &(head  -> books).wholesale_purchased);

建议:不要忽略编译器警告并使用GDB进行调试。


0
投票

问题出在这里,

typedef struct bookData{
char bookTitle[35];
char author[35];
int book_stock;
float retail_price;
int wholesale_purchased;
int customer_purchased;
struct bookData *book;
}new_book;

用以下内容更改:

typedef struct bookData{
char* bookTitle;
char* author;
int book_stock;
float retail_price;
int wholesale_purchased;
int customer_purchased;
struct bookData *book;
}new_book;

或者使用achals回答中建议的strcpy()函数。在LHS中,您使用的数组类型不可分配。所以你必须用strcpy()复制它或复制已分配的字符串的指针。

其他解决方案是使用

 head->books = (new_book){bookTitle,author};

这不是直接的任务,所以它会起作用。

© www.soinside.com 2019 - 2024. All rights reserved.