printf在特定的上下文中不起作用,为什么?

时间:2020-05-24 13:48:45

标签: c printf strcmp

我需要测试一些东西,并对这小段代码进行编程(如下所示)。我不明白为什么第一张印刷作品有效而第二张印刷作品无效。该程序的输出仅为

    this prints

但应该是

    this prints
    this doesn't print i: 1

这是代码:

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

int cmp(char *str) {
    char *z[1];
    strcpy(*z, "z");
    int a;

    a = strcmp(str, *z);

    return a;
}

int main() {
    int i;
    char *name[1];
    printf("this prints\n");

    strcpy(*name, "y");
    i = cmp(*name);
    printf("this doesn't print i:%d", i);
    return 0;
}

2 个答案:

答案 0 :(得分:3)

char *z[1]; // this is an array of pointer
strcpy(*z, "z"); // you have to allocate at least 2 bytes for *z

// and
char *name[1];
strcpy(*name, "y"); // you have to allocate at least 2 bytes for *name also

您没有在数组zname中分配指针。

您的cmp函数看起来很奇怪。如果您想将字符串与"z"进行比较,则可以执行以下操作:

int cmp(char *str){
   return strcmp(str, "z");
}

您无需使用char *name[1],只需使用char *name = malloc(SIZE+1);char name[SIZE+1]SIZE是您要比较的字符串的长度)就足够了。

答案 1 :(得分:1)

char *z[1];char *name[]

  1. namez都不是char的数组。它们都是指向char的一个指针的数组。

  2. 两个指针name[1]z[1]都指向无效内存,因此将其取消引用并尝试使用strcpy(*name, "y");和{{1}将字符串存储到该未定义的内存中}并调用undefined behavior。 -您需要的是strcpy(*z, "z");char的{​​{1}}数组。

  3. 要存储字符串,您需要一个元素来存储以字符串结尾的空字符。

如果您只想让字符串包含一个字符,请使用namez


顺便说一句,您的代码有点复杂。如果只想存储和比较单个字符,则不要使用字符串。可以简化为:

char z[2]

输出:

name[2]

其中#include <stdio.h> int main (void) { char name = 'y'; printf("In name is the character: '%c'\n", name); printf("Is the character 'z' in 'name'? %d", name == 'z'); return 0; } 表示In name is the character: 'y' Is the character 'z' in 'name'? 0 ,而0表示false


旁注:

您无需在任何时间1