This is what Im trying to achieve if possible but am getting garbage values in struct array member
s elements.
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
struct _time{
char _second[3];
char _minute[3];
char _hour[3];
char _monthDay[3];
char _month[4];
char _year[3];
};
struct _time get_time(void);
void prefix_shm(char *a);
int main(void){
struct _time my_time=get_time();
printf("seconds=%s\n",my_time._second);
return 0;
}
struct _time get_time(void){
char _seconds[3]={0};
char _minute[3]={0};
char _hour[3]={0};
char _monthDay[4]={0};
char _month[3]={0};
char _year[3]={0};
strcpy(_seconds,"1");
//prefix_shm(_seconds);
strcpy(_minute,"1");
//prefix_shm(_minute);
strcpy(_hour,"1");
strcpy(_monthDay,"1");
strcpy(_month,"1");
strcpy(_year,"1");
return (struct _time){_seconds,_minute,_hour,_monthDay,_month,_year};
};
void prefix_shm(char *a) {
if (strlen(a) == 1 ) {
a[1] = a[0];
a[0] = '0';
}
}
If I will make a struct inside a function and return it its working.
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
struct _time{
char _second[3];
char _minute[3];
char _hour[3];
char _monthDay[3];
char _month[4];
char _year[3];
};
struct _time get_time(void);
void prefix_shm(char *a);
int main(void){
struct _time my_time=get_time();
printf("seconds=%s\n",my_time._second);
return 0;
}
struct _time get_time(void){
struct _time my_time={{0},{0},{0},{0},{0},{0}};
strcpy(my_time._second,"2");
prefix_shm(my_time._second);
strcpy(my_time._minute,"2");
prefix_shm(my_time._minute);
strcpy(my_time._hour,"3");
strcpy(my_time._monthDay,"4");
strcpy(my_time._month,"5");
strcpy(my_time._year,"6");
return my_time;
};
void prefix_shm(char *a) {
if (strlen(a) == 1 ) {
a[1] = a[0];
a[0] = '0';
}
}
Because first option is working with struct containing integers:
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
struct _time{
int a;
int b;
};
struct _time get_time(void);
void prefix_shm(char *a);
int main(void){
struct _time my_time=get_time();
printf("seconds=%d\n",my_time.a);
return 0;
}
struct _time get_time(void){
return (struct _time){1,2};
};
void prefix_shm(char *a) {
if (strlen(a) == 1 ) {
a[1] = a[0];
a[0] = '0';
}
}
Is there way to make first option working or I have to declare struct same type in the function like in 2-nd code?
Thanks.