I needed to test something and programmed this little bit of code(shown below). I can't understand why the first print works and the second doesn't. The output of this program is just
this prints
but it should be
this prints this doesn't print i: 1
Here's the code:
#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
You did not allocate for the pointer in array z
and name
.
Your cmp
function looks weird. If you want to compare string with "z"
, you can just do:
int cmp(char *str){
return strcmp(str, "z");
}
You do not need to use char *name[1]
, just char *name = malloc(SIZE+1);
or char name[SIZE+1]
( SIZE
is length of string that you want to compare) is enough.
char *z[1];
and char *name[]
Both name
and z
are not arrays of char
. They are both an array of one pointer to char
.
Both pointers name[1]
and z[1]
point to no valid memory, thus dereferencing it and attempting to store a string to that undefined memory by using strcpy(*name, "y");
and strcpy(*z, "z");
and invokes undefined behavior . - What you need is an array of char
for both, name
and z
.
For storing a string you need one element to store the string-terminating null character.
Use char z[2]
and name[2]
, if you only want to have strings contained of one single character.
BTW, Your code is a little bit complicate handled. You do not to use strings if you want to store and compare only single characters. It could be simplified as:
#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
Where 0
means false
and 1
signifies true
.
Side Note:
You didn´t need to #include <stdlib.h>
at any point of time.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.