无法将字符串文字分配给 C 中的字符数组

问题描述 投票:0回答:1

我正在尝试将字符串文字分配给字符数组。

这段代码运行良好

#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;

}

编译器给我的错误:

错误(活动)E0513 类型“const char *”的值不能分配给类型“char *”的实体 结构指针和函数 F:\Mohamed Taha\Codes\C 编程\C 初学者编程 s\结构指针和函数\结构指针和函数\mian.cpp 41

我像往常一样尝试先询问chatgpt,但它没有给我任何解释。它说错误是因为字符串文字是在内存上读取的,因此您无法写入它们,但它没有任何意义,因为第一个代码有效。

注:

两段代码在同一个编译器上运行。

c pointers c-strings string-literals
1个回答
0
投票

您无法更改只读内存,这就是使用字符串文字最终得到的结果:

item1.itemName = "SDfsd";

声明一个指向char(char *)类型指针的变量并不会为字符串保留内存(实际上C中没有字符串,只有char数组)。所以需要分配内存,例如:

item1.itemName = (char*) malloc(100);

另一个问题是您混淆了 NULL(值为 0 的 int)和空字符。你应该使用

p->itemName[i] = ' ';

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