While creating strjoin I noticed a strange phenomenon. When outputting a value strs in function strjoin()
These results were printed
123
Why?
#include <stdio.h>
#include <stdlib.h>
char *strjoin(int size, char **strs, char *sep)
{
char *new;
if (!(new = malloc(sizeof(char) * size)))
return (NULL);
printf("%s", strs[1]);
return (NULL);
}
#include <unistd.h>
int main(void)
{
char* b[4] = {"123", "456", "789", "245"};
char *p;
int i = 0;
int size = 5;
char a[4] = {',', 'a', 'b', '\0'};
p = *b;
strjoin(5, &p, a);
}
In order for it to be valid to use the value referenced by str[1]
, str
must point to an array of at least two char*
elements. In your demonstration, it points to p
, which is a single char*
. Your program therefore invokes Undefined Behaviour , and thus your program is invalid.
It's unclear what you are trying to accomplish. Perhaps you wanted
char **p = &( b[0] );
strjoin(4, p, a)
Keep in mind that an array used where a pointer is expected degenerates into a pointer to its first elements, so the above is equivalent to the following:
char **p = b;
strjoin(4, p, a)
or simply
strjoin(4, b, a)
(The first parameter to strjoin
isn't being used in your demonstration, but I imagine it's expected to be the number of elements in *str
, so I have adjusted it the argument accordingly.)
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.