Arrays 使用指向struct的指针为char字符串赋值 #包括 #包括 //结构定义 结构日期 { 查日[10]; 半个月[3]; 国际年; }斯代特; //声明的函数 作废存储打印日期(结构日期*); 空干管() { 结构日期*datePtr=NULL; datePtr=&sdate; store_print_date(datePtr);//调用函数 } 作废存储\打印\日期(结构日期*日期ptr) { datePtr->day=“星期六”//此处出错 datePtr->month=“Jan”//此处相同 日期->年份=2020年; }
您需要使用Arrays 使用指向struct的指针为char字符串赋值 #包括 #包括 //结构定义 结构日期 { 查日[10]; 半个月[3]; 国际年; }斯代特; //声明的函数 作废存储打印日期(结构日期*); 空干管() { 结构日期*datePtr=NULL; datePtr=&sdate; store_print_date(datePtr);//调用函数 } 作废存储\打印\日期(结构日期*日期ptr) { datePtr->day=“星期六”//此处出错 datePtr->month=“Jan”//此处相同 日期->年份=2020年; },arrays,c,function,pointers,struct,Arrays,C,Function,Pointers,Struct,您需要使用strcpy()方法将字符串复制到字符数组中(注意注释): 请使用strcpy()复制字符串。反正char月[3]不够大,无法容纳3个字符(以null结尾)的字符串。它在我添加错误注释的datePtr上显示错误…错误是“表达式必须是可修改的左值”“Saturday”解析为指针,但datePtr->day是数组。您可以修改datePtr->day[0]等,但不能修改datePtr->day。太好了!这是有效的。谢谢 #include<stdio.h> #include<
strcpy()
方法将字符串复制到字符数组中(注意注释):
请使用strcpy()复制字符串。反正
char月[3]代码>不够大,无法容纳3个字符(以null结尾)的字符串。它在我添加错误注释的datePtr上显示错误…错误是“表达式必须是可修改的左值”“Saturday”
解析为指针,但datePtr->day
是数组。您可以修改datePtr->day[0]
等,但不能修改datePtr->day
。太好了!这是有效的。谢谢
#include<stdio.h>
#include<stdlib.h>
//structure defined
struct date
{
char day[10];
char month[3];
int year;
}sdate;
//function declared
void store_print_date(struct date *);
void main ()
{
struct date *datePtr = NULL;
datePtr = &sdate;
store_print_date(datePtr); // Calling function
}
void store_print_date(struct date *datePtr)
{
datePtr->day = "Saturday"; // error here
datePtr->month = "Jan"; // same here
datePtr->year = 2020;
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// structure defined
struct date
{
char day[10];
char month[4]; // +1 size 'cause NULL terminator is also required here
int year;
} sdate;
// function declared
void store_print_date(struct date *);
int main(void) // always return an integer from main()
{
struct date *datePtr = NULL;
datePtr = &sdate;
store_print_date(datePtr); // Calling function
return 0;
}
void store_print_date(struct date *datePtr)
{
strcpy(datePtr->day, "Saturday"); // using strcpy()
strcpy(datePtr->month, "Jan"); // again
datePtr->year = 2020; // it's okay to directly assign since it's an int
printf("%s\n", datePtr->day); // successful
printf("%s\n", datePtr->month); // output
}
Saturday // datePtr->day
Jan // datePtr->month