使用了未初始化的局部变量

时间:2016-02-25 11:47:16

标签: c

我的代码出现以下错误:

  

错误C4700:未初始化的本地变量' str_day'使用

我在Visual Studio Express 2012中编译

这是我的代码:

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

void separate (char *join, char *tempmonth, int *tempday){
    //function to separate month and day from a string
    char *p ;
    p = strtok(join," ");
    strcpy(tempmonth,p);                    // Write the month in tempmonth 
    p = strtok(NULL," ");
    *tempday = atoi(p);                     // Write the day to tempday
}   

int main(){
    char month[20],tempmonth[20],join[30];
    char *str_day;
    int day,tempday;
    printf("Enter the month: ");
    scanf("%s",month);
    printf("Enter the day: ");
    scanf("%d",&day);
    strcpy(join,month);                         
    strcat(join," ");                               //add the month and day seperating by space
    sprintf(str_day,"%d",day);                      //convert day to string to concatenate with month
    strcat(join,str_day);
    separate(join,tempmonth,&tempday);              //call to function separate 
    printf("Month: %s, Day: %d\n",tempmonth,tempday);

    return 0;
}

任何人都可以帮我找出错误吗?

2 个答案:

答案 0 :(得分:3)

替换

char *str_day;

char *str_day = malloc(n * sizeof(char)); 

其中n是您想要的字符数。 str_day必须显示在某处(换句话说,初始化)才能使用它。 否则,请使用字符数组,例如

char str_day[n]; 

其中n是你想要的字符数。

答案 1 :(得分:1)

您的问题是@Override public void onScrollChanged() { if (webview.getScrollY() == 0) { swipeLayout.setEnabled(true); } else { swipeLayout.setEnabled(false); } }

的声明和用法
str_day

char *str_day; sprintf(str_day,"%d",day); 是一个未初始化的指针。它的值是不确定的,甚至访问它的值(将该值传递给str_day)也会产生未定义的行为。这就是编译器警告的内容。

更糟糕的是,sprintf()会将其收到的任何值视为sprintf()的数组,其长度足以将char的值写入day格式。结果 - 因为%d未初始化 - 也未定义。在实践中,str_day可能会覆盖它应该没有的记忆。

要解决此问题,请将sprintf()更改为char

数组
str_day

或为其分配缓冲区以指向。

char str_day[10];

在上述两种情况下,我假设9个字符足以容纳char *str_day = malloc(10); /* do your work here */ free(str_day); /* when finished with it */ 的值。

相关问题