我正在try 将字符串字面赋值给字符array.
这段代码运行良好
#include <stdio.h>
struct student
{
char* name;
};
struct student s[2];
void main()
{
s[0].name = "jason";
s[1] = s[0];
printf("%s%s", s[0].name, s[1].name);
s[1].name = "fedin";
printf("%s%s", s[0].name, s[1].name);
}
但这段代码不起作用:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
struct item {
char* itemName;
int quantity;
float price;
float amount;
};
void readItem(item* const p) {
printf("Please enter item name. \n");
fgets(p->itemName, 50, stdin);
for (int i = 0; i < strlen(p->itemName); i++)
{
if (p->itemName[i] == '\n') {
p->itemName[i] = NULL;
}
}
printf("Please enter the quantity. \n");
scanf_s("%d", &p->quantity);
printf("Please enter the price. \n");
scanf_s("%f", &p->price);
}
void print(item* const p) {
printf("Item Name: %s \n", p->itemName);
printf("Quantity: %i \n", p->quantity);
printf("Price: %.4f \n", p->price);
p->amount = (p->quantity) * (p->price);
printf("Amount: %.4f \n", p->amount);
}
int main(void) {
struct item item1;
item1.itemName = "SDfsd";
item1.quantity = 0;
item1.price = 0.0;
item1.amount = 0.0;
struct item* itemP = &item1;
readItem(itemP);
print(itemP);
free(itemP->itemName);
itemP->itemName = NULL;
return 0;
}
编译器给我的错误:
Error (active) E0513 a value of type "const char *" cannot be assigned to an entity of type "char *" Structure Pointers and Functions F:\Mohamed Taha\Codes\C Programming\C Programming For Beginners\vs\Structure Pointers and Functions\Structure Pointers and Functions\mian.cpp 41
像往常一样,我试着先问ChatGPT,但它没有给我任何解释.它说错误是因为字符串文字在只读内存中,所以您不能写入它们,但这没有任何意义,因为第一个代码可以工作.
注意:这两段代码在同一个编译器上运行.