首页 > 解决方案 > 使用指向结构的指针为字符字符串赋值

问题描述

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

标签: arrayscfunctionpointersstruct

解决方案


您需要使用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

推荐阅读