繁体   English   中英

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

[英]printf doesn't work on specific context, why?

我需要测试一些东西并编写一小段代码(如下所示)。 我不明白为什么第一次打印有效而第二次无效。 这个程序的output就是

    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;
}
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 function 看起来很奇怪。 如果您想将字符串与"z"进行比较,您可以这样做:

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

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

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

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

  2. 指针name[1]z[1]都指向无效的 memory,因此取消引用它并尝试使用strcpy(*name, "y"); strcpy(*z, "z"); 并调用未定义的行为 - 您需要的是namezchar数组。

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

如果您只想让字符串包含一个字符,请使用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;
}

Output:

In name is the character: 'y'
Is the character 'z' in 'name'? 0

其中0表示false1表示true


边注:

您在任何时候都不需要#include <stdlib.h>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM