简体   繁体   English

C:字符串变量从无效返回后丢失值 Function

[英]C: String Variable Loses Value After Returning From Void Function

hope you are well.希望你一切都好。

I recently started learning ADT (Abstract Data Type) in college, and I have an assignment that states the following:我最近开始在大学学习 ADT(抽象数据类型),并且我的作业说明了以下内容:

Complete ADTDate adding the following primitive function:完成 ADTDate 添加以下原语 function:

void dayWeekStr(DatePtr date,char *buffer)// places the day of the week of the date in buffer void dayWeekStr(DatePtr date,char *buffer)// 将日期的星期几放入缓冲区

So in main() you define a char pointer, and send it to the function alongside the date struct .因此,在main()中,您定义了一个 char 指针,并将其与 date struct一起发送到 function 。 Basically what the function does is, it calls a getter to obtain the Gregorian Day in form of a number (I'm storing the dates in Julian Days);基本上 function 所做的是,它调用 getter 以数字形式获取公历(我将日期存储在儒略日); this is, from 0 (sunday) to 6 (saturday), and from that I have a switch that assigns each day in form of a string ("Tuesday") to buffer.这是从 0(星期日)到 6(星期六),然后我有一个开关,它以字符串(“星期二”)的形式将每一天分配给缓冲区。 It looks like this:它看起来像这样:

void dayWeekStr(DatePtr date,char *buffer)
{
    switch (dayWeek(date))
    {
        case 0:
            buffer="Sunday";
            break;
        case 1:
            buffer="Monday";
            break;
        case 2:
            buffer="Tuesday";
            break;
        case 3:
            buffer="Wednesday";
            break;
        case 4:
            buffer="Thursday";
            break;
        case 5:
            buffer="Friday";
            break;
        case 6:
            buffer="Saturday";
            break;
        default:
            printf("ERROR\n");
            break;
    }
}

Back in main() you print it and that's it.回到main()你打印它,就是这样。 My main looks like this:我的主要看起来像这样:

int main()
{
    int d=0,m=0,y=0;
    printf("DD MM YYYY: ");
    scanf("%d %d %d",&d,&m,&y);
    printf("\n");
    DatePtr date1=createDate(d,m,y);
    char *s=getDinamicShortDate(date1);
    char *strDay;
    dayWeekStr(date1,strDay);
    printf("Date: %s, %s\n",strDay,s);

    date1=destroyDate(date1);
    free(s);
    s=NULL;
    return 0; 
}

So when I run it, I expect this:所以当我运行它时,我期望这样:

DD MM AAAA: 9 9 2022
    
Fecha: Friday, 9/9/2022

But instead, this is the result:但是,结果如下:

DD MM AAAA: 9 9 2022

Fecha:

I really don't know what happened.我真的不知道发生了什么。 I tried printing buffer 's value inside the function, and it seems it stores it, but then in main it doesn't.我尝试在 function 中打印buffer的值,它似乎存储了它,但主要它没有。

I also tried changing the function to我还尝试将 function 更改为

char *dayWeekStr(DatePtr date)

so it actually returns a string after the switch:所以它实际上在切换后返回一个字符串:

char *dayWeekStr(DatePtr date)
{
    switch (dayWeek(date))
    {
        case 0:
            return "Sunday";
            break;
        case 1:
            return "Monday";
            break;
        case 2:
            return "Tuesday";
            break;
        case 3:
            return "Wednesday";
            break;
        case 4:
            return "Thursday";
            break;
        case 5:
            return "Friday";
            break;
        case 6:
            return "Saturday";
            break;
        default:
            return "-1";
            break;
    }
}

In main it only changes from在主要它只改变从

char *strDay;
dayWeekStr(date1,strDay);

to

char *strDay=dayWeekStr(date1);

and it does work.它确实有效。 I believe the problem has something to do with the char pointer variable retaining its value after exiting the void function, but what's the issue here?我认为问题与退出 void function 后保留其值的 char 指针变量有关,但这里有什么问题?

You have passed the value of the pointer to your function, which is stored in a local variable.您已将指针的传递给存储在局部变量中的 function。 Assigning to that local variable does nothing to the original pointer, but if we used string functions which use the value in that pointer, we can.分配给该局部变量对原始指针没有任何作用,但是如果我们使用使用该指针中的值的字符串函数,我们可以。 For instance, using strcpy to copy the correct string into the buffer pointed to by the function argument.例如,使用strcpy将正确的字符串复制到 function 参数指向的缓冲区中。

#include <string.h>
#include <stdio.h>

void weekday(int day, char *buffer) {
  char *days[] = {
    "Sunday", "Monday", "Tuesday", "Wednesday",
    "Thursday", "Friday", "Saturday"
  };

  if (day <= 6 && day >= 0) {
    strcpy(buffer, days[day]);
  }
  else {
    strcpy(buffer, "-1");
  }
}

int main(void) {
  int day = 2;
  char day_of_week[20] = {0};

  weekday(day, day_of_week);

  printf("%s\n", day_of_week);

  return 0;
}

Note also that rather than using a long switch statement or if/else, I've simply indexed into an array of strings.另请注意,我没有使用长 switch 语句或 if/else,而是简单地索引到一个字符串数组。 Remember this pattern anytime you are using a switch for a lookup with sequential numbers.每当您使用开关查找序列号时,请记住此模式。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM