c - 如何在函数内打印指向字符数组的指针?

标签 c string pointers printf scanf

我正在尝试用 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。当我的代码到达那条线时它就会刹车。我该如何解决这个问题?

最佳答案

错误:

  1. 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

  2. 您将无限长度的字符串读入固定长度的缓冲区: buffer-overflow: UB
    使用%999s 999 个字符加上哨兵

  3. 您在调用 scanf 时没有检查错误,可能导致使用未初始化的缓冲区:可能找不到终止符:UB
  4. 您比较两个指针是否相等(以及字符串是否相同),而不是字符串是否相等。包括<string.h>并使用

    if(!strcmp(first, second))
    

其他观察结果:

  1. return EXIT_SUCCESS;是多余的,main有隐式return 0;自C99以来的最后。
    • 这使得#include <stdlib.h>多余的。
  2. 在首次使用之前定义函数可以让您放弃前向声明。

关于c - 如何在函数内打印指向字符数组的指针?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25831179/

相关文章:

c - 删除链接排序列表中的第一个元素

c - libxml2 所有 xml 转 char

c - 链表C中的无限while循环

c - 当我尝试使用 strncpy 将一个数组缓冲区复制到另一个数组缓冲区时,为什么会出现不兼容的指针类型错误?

C:解析输入文件以检查格式

c - 头文件包括 conio.h 吗?

java - #define 在 java/android studio 中使用

python - 使用 Pandas 将字符串格式化为日期时间 - 指令有问题

php - 安全字符串比较功能

c++ - 为什么多维数组中的空字符串文字会衰减为空指针?