[英]Assigning value to char string using pointer to struct
#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;
}
You need to use strcpy()
method to copy the string into the character array (note the comments):您需要使用
strcpy()
方法将字符串复制到字符数组中(注意注释):
#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
}
It'll display:它会显示:
Saturday // datePtr->day
Jan // datePtr->month
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.