Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
298 views
in Technique[技术] by (71.8m points)

arrays - 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;
}
question from:https://stackoverflow.com/questions/65644660/assigning-value-to-char-string-using-pointer-to-struct

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You need to use strcpy() method to copy the string into the character array (note the comments):

#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
", datePtr->day);     // successful
    printf("%s
", datePtr->month);   // output
}

It'll display:

Saturday  // datePtr->day
Jan       // datePtr->month

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...