arrays - 使用指向结构的指针为字符字符串赋值
问题描述
#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;
}
解决方案
您需要使用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
}
它会显示:
Saturday // datePtr->day
Jan // datePtr->month
推荐阅读
- android - Flutter:未应用自定义字体系列
- android - 如何在我的应用程序中包含 QR 码功能?
- mysql - 在 laravel 中具有 2 个表选择的等效查询生成器表达式是什么
- android - 在 Android for Flutter 中,'getApplicationContext()' 的替代方法是什么
- c# - 如何解决 bot 框架模拟器上发生 POST401directline.postActivity 错误?
- spring - 没有找到适用于 create() 方法 reactor.test.StepVerifier.create 的方法
- android - tablayout 的屏幕截图程序不会发生在第 4 个和更高的选项卡上
- java - 如何使用 Maven 在 Heroku 上运行测试
- python - Pandas 根据条件在多列中找到第一个非零条目
- angular - 带有 @Input() 的 Angular ExpressionChangedAfterItHasBeenCheckedError 到子视图