【问题标题】:Assigning value to char string using pointer to struct使用指向结构的指针为字符字符串赋值
【发布时间】:2021-04-15 02:02:54
【问题描述】:
#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()复制字符串。无论如何,char month[3]; 不足以容纳 3 个字符(和以 null 结尾)的字符串。
  • 它在 datePtr 上显示错误,我添加了错误注释......并且错误是说“表达式必须是可修改的左值”
  • "Saturday" 解析为一个指针,但 datePtr-&gt;day 是一个数组。可以修改datePtr-&gt;day[0]等,但不能修改datePtr-&gt;day

标签: arrays c function pointers struct


【解决方案1】:

您需要使用strcpy() 方法将字符串复制到字符数组中(注意cmets):

#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

【讨论】:

    猜你喜欢
    • 2020-03-23
    • 2020-10-30
    • 2021-05-22
    • 2016-12-30
    • 1970-01-01
    • 1970-01-01
    • 2013-04-26
    • 1970-01-01
    相关资源
    最近更新 更多