在这个问题,有人建议意见,我应该不会投的结果malloc,即
int *sieve = malloc(sizeof(int) * length);
Run Code Online (Sandbox Code Playgroud)
而不是:
int *sieve = (int *) malloc(sizeof(int) * length);
Run Code Online (Sandbox Code Playgroud)
为什么会这样呢?
以下是否会在第4行和/或第5行中引发未定义的行为:
#include <stdio.h>
int main(void)
{
char s[] = "foo";
char * p = s - 1; /* line 4 */
printf("%s\n", p + 1); /* line 5 */
return 0;
}
Run Code Online (Sandbox Code Playgroud) 据说我们可以编写多个声明但只能编写一个定义.现在,如果我使用相同的原型实现我自己的strcpy函数:
char * strcpy ( char * destination, const char * source );
Run Code Online (Sandbox Code Playgroud)
那么我不是在重新定义现有的库函数吗?这不应该显示错误吗?或者它是否以某种方式与库函数以目标代码形式提供的事实有关?
编辑:在我的机器上运行以下代码说"分段故障(核心转储)".我正在使用linux并且已经编译而没有使用任何标志.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strcpy(char *destination, const char *source);
int main(){
char *s = strcpy("a", "b");
printf("\nThe function ran successfully\n");
return 0;
}
char *strcpy(char *destination, const char *source){
printf("in duplicate function strcpy");
return "a";
}
Run Code Online (Sandbox Code Playgroud)
请注意,我不是要尝试实现该功能.我只是想重新定义一个函数并询问后果.
编辑2:在应用Mats建议的更改后,程序不再提供分段错误,尽管我仍在重新定义函数.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *strcpy(char *destination, const char *source);
int main(){
char *s = strcpy("a", "b");
printf("\nThe function ran successfully\n");
return …Run Code Online (Sandbox Code Playgroud)