我需要测试一些东西,并对这小段代码进行编程(如下所示)。我不明白为什么第一张印刷作品有效而第二张印刷作品无效。该程序的输出仅为
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;
}
答案 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
您没有在数组z
和name
中分配指针。
您的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[]
name
和z
都不是char
的数组。它们都是指向char
的一个指针的数组。
两个指针name[1]
和z[1]
都指向无效内存,因此将其取消引用并尝试使用strcpy(*name, "y");
和{{1}将字符串存储到该未定义的内存中}并调用undefined behavior。 -您需要的是strcpy(*z, "z");
和char
的{{1}}数组。
要存储字符串,您需要一个元素来存储以字符串结尾的空字符。
如果您只想让字符串包含一个字符,请使用name
和z
。
顺便说一句,您的代码有点复杂。如果只想存储和比较单个字符,则不要使用字符串。可以简化为:
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
。