簡體   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