我正在尝试用 c 语言进行自己的简单测试。这是我的尝试:
#include <stdio.h>
#include <stdlib.h>
void assert(char *first, char *second);
int main(void) {
char first[1000];
char second[1000];
printf("Enter first string: ");
scanf("%s", first);
printf("Enter second string: ");
scanf("%s", second);
assert(*first, *second);
return EXIT_SUCCESS;
}
void assert(char *first, char *second){
if( first == second ){
printf("Test Passed: these strings are the same");
}else{
printf("Test Failed: expected %s but returned %s", first, second);
}
}
问题出在assert中else语句中的printf。当我的代码到达那条线时它就会刹车。我该如何解决这个问题?
最佳答案
错误:
assert
可能由实现定义,通过外部链接自行定义是 Undefined Behavior (UB) .7.2 Diagnostics
<assert.h>
[...]
2 The assert macro shall be implemented as a macro, not as an actual function. If the macro definition is suppressed in order to access an actual function, the behavior is undefined您将无限长度的字符串读入固定长度的缓冲区: buffer-overflow: UB
使用%999s
999 个字符加上哨兵- 您在调用
scanf
时没有检查错误,可能导致使用未初始化的缓冲区:可能找不到终止符:UB 您比较两个指针是否相等(以及字符串是否相同),而不是字符串是否相等。包括
<string.h>
并使用if(!strcmp(first, second))
其他观察结果:
-
return EXIT_SUCCESS;
是多余的,main
有隐式return 0;
自C99以来的最后。- 这使得
#include <stdlib.h>
多余的。
- 这使得
- 在首次使用之前定义函数可以让您放弃前向声明。
关于c - 如何在函数内打印指向字符数组的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25831179/