如何解决“ [某物]可能在此功能中未初始化使用”的警告?

时间:2019-11-12 05:10:21

标签: c gcc-warning

我正在尝试执行字符串复制命令,但是在编译程序时出现编译警告(请参见标题)。如果我在不使用-Wall选项的情况下编译代码,则它可以为我提供正确的输出,但是我想在-Wall进行编译并且不会收到任何警告。我该如何解决我的问题?我已经用谷歌搜索了,但我听不懂。

当我将str2初始化为NULL0时,它会给我段错误。

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

void my_strcpy(char *dest[], const char *src[]);

int main(){

  char *str1, *str2;
  int i;

  printf("What is the longest length of a string that you will enter?");
  scanf("%i",&i);

  str1=malloc(i * sizeof(char));
  if (str1 == NULL){
    printf("\n malloc failed to allocate enough memory!\n");
    return 1;
  }

  printf("Enter a string: ");
  scanf("%s", str1);

  my_strcpy(str2,str1);
  printf("%s \n", str1);
  return 0;
}

void my_strcpy(char *dest, const char *src)
{
  int i;

  for(i=0; src[i]!='\0'; i++)
    dest[i]=src[i];
}

我希望输出仅显示一个字符串,例如:

  

输入文字:世界你好

输出:

  

你好

1 个答案:

答案 0 :(得分:2)

解决编译器警告所需的内容很少:

  1. my_strcpy的函数原型。考虑将原型与实现相匹配:void my_strcpy(char *dest, const char *src);,而不是void my_strcpy(char *dest[], const char *src[]);

  2. str2的分配。它被声明为指针,但未分配空间。考虑添加str2 = malloc(i+1);或类似的内容。

  3. str1的分配(运行时错误,不是编译器警告)。请记住为终端NUL字节添加空间:str1=malloc((i+1) * sizeof(char));而不是str1=malloc(i * sizeof(char));