Writing into a malloc string
I'm new to C programming language, and malloc precisely. So I created this program to take arguments from argv and put them all in a single string, separated by spaces(on line 32). But when I run it, everything works out, but there seems to be no spaces inserted as desired in the code below.
When I tried commenting, line 28: buffer[t] = argv[str][i];
the spaces appear.
I also tried casting: malloc(buffSize)
to (char*)
before assigning it to buffer to just see if anything changes¿¿. But nothing.
Please I'd be glad if someone can clear me out on what's going on. Thanks in advance 🙏🏼
#include <stdio.h>
#include <stdlib.h>
int main()
{
int str = 0, i = 0, t = 0, letterCount = 0, buffSize;
char *buffer;
char *argv[] = {"hello", "me", "too"};
int argc = 3;
while (str < argc)
{
while (argv[str][i++])
letterCount++;
str++;
i = 0;
}
buffSize = letterCount + argc + 1;
str = 0;
buffer = (char*) malloc(buffSize);
if (!buffer)
return (NULL);
while (str < argc)
{
while (argv[str][i] != '\0')
{
buffer[t] = argv[str][i];
t++;
i++;
}
buffer[t] = ' ';
str++;
i = 0;
}
printf("%s", buffer);
return (0);
}
Comments
Post a Comment