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);
}
sizeof (char)always equals to one then redundant.pis located afterbon stack (hence, has lower address). You're passing address ofp, but it is only 1 element, so indexes greater than 0 actually reference values fromb, e.g.strs[1]isb[0].return 0can be omitted frommain.return EXIT_SUCCESS;is optional according to the C language, even when declared asint main(...). (In fact,mainmust be declared to returnintin C99.) Note that I didn't mention any compiler or version thereof.