基本功能的C编译错误

C compilation error for basic function

我正在尝试编写我自己的 strcat 版本(我称之为 "append")。这是我拥有的:

#include <stdio.h>

int main() {

  char *start = "start";
  char *add = "add";
  append(start, add);
  printf(start);

}

void append(char *start, char *add) {
  //get to end of start word
  char *temp = &start;
  while (*temp != '[=10=]') {
    temp++;
  }
  *temp = *add;
  while (*temp != '[=10=]') {
     *temp = *add; 
  }
}

当我编译时,我收到 3 个警告和一个错误:

1) warning: implicit declaration of function 'append' is invalid in C99

2) warning: format string is not a string literal (potentially insecure)

3) error: conflicting types for 'append'

我没有看到我在 main 中传递到我的附加函数的参数如何与它下面的函数定义冲突。

4) warning: incompatible pointer types initializing 'char *' with an expression of type 'char **'; remove &

为什么我要在此处删除 &?我想我可以一次声明并初始化我的 char 指针到正确的内存地址。

非常感谢任何帮助。

1) warning: implicit declaration of function 'append' is invalid in C99

3) error: conflicting types for 'append'

因为,你在使用前没有提供append()的原型。您需要在使用函数之前添加函数的前向声明。添加

void append(char *start, char *add);

main()之前或将函数定义放在main()

之前

接下来,如果

 char *start = "start";
 char *add = "add";

startadd 是指向 字符串文字 的指针。它们通常放在只读存储器中,这意味着您不能更改其中的内容。任何这样做的尝试都会导致 undefined behavior.

那么,关于

2) warning: format string is not a string literal (potentially insecure)

printf(start);

在这种情况下是错误的用法。你需要像

一样使用它
printf("%s\n", start);

查看 printf()man page 了解更多详情。

最后,

4) warning: incompatible pointer types initializing 'char *' with an expression of type 'char **'; remove &

是因为

char *temp = &start;

你需要使用像

这样的东西
char *temp = start;   //start is a char *, no need for & here

注:main()推荐签名为int main(void).

您对该短代码有多个问题。首先你有

warning: implicit declaration of function 'append' is invalid in C99

这个警告的意思是你需要声明函数才能使用它们。如果你在使用一个函数之前没有声明它,编译器将不得不猜测它的参数和 return 类型,而且通常它猜得很糟糕。

继续下一个警告:

warning: format string is not a string literal (potentially insecure)

这是因为您向 printf 提供了一个字符串变量,正如警告告诉您的那样,这是不安全的。例如,考虑这样一种情况,您从用户那里读取输入,并将该输入用作 printf 的格式字符串。什么会阻止用户在输入字符串中添加格式代码?由于您不传递参数,这些格式的参数从何而来?

现在错误:

error: conflicting types for 'append'

这是因为第一个问题,编译器错误地猜测了函数的参数或 return 类型。


现在讨论另一个主要 问题,它没有显示为编译器错误或警告,即undefined behavior

问题是您的 startadd 变量指向字符串文字。字符串文字是只读(实际上,字符串文字是指向不可修改字符数组的指针)。第一个问题是您尝试修改这些数组的内容,第二个问题是数组的大小仅根据需要而定,并且您正在该内存之外写入。这两个问题都是 未定义行为.

的原因

但这是最​​简单的部分,编译器可以检测到。

更糟糕的是,当您将 start 声明为 char *start = "start" 时,它仅指向 6 个字符的数组(5 个字母 + 终止空值)。

因此,当您尝试在其末尾添加 add 时,您会得到未定义的行为(用于超出和写入数组)!在那种情况下,您正在编写内存,而其他内存可能存在 => 您的程序可能会中断或出现段错误。

C99 在它希望您声明事物的方式上有相当的限制。

正如 Sourav 所说, 1 & 3 是由 append() 函数在文件中声明之前使用引起的,这会导致编译器为您生成隐式声明。将 append() 函数移动到 main() 上方以修复该问题(或添加函数原型)。

4 是由这一行引起的:char *temp = &start;

temp 这里实际上是一个 char**,因为你取的是 char*

的地址