I'm trying to add characters to a string one by one. I have something like this:
void doline(char *line, char *buffer, char** tokens){
}
and i am calling it like:
char *line = malloc(1025 * sizeof(char *));
fgets(line, 1024, stdin);
int linelength = strlen(line);
if (line[linelength - 1] == '\n'){
line[linelength - 1] = '\0';
}
char ** tokens = (char **) malloc(strlen(line) * sizeof(char *));
char *emptybuffer = malloc(strlen(line) * sizeof(char *));
parseline(line, emptybuffer, tokens);
So doline will go through line and tokenize it based on various conditions and place fragments of it into tokens. I am building the temp string in the variable buffer To do this, I need to go through line character by character.
I am currently doing:
buffer[strlen(buffer)] = line[i];
And then at the end of the loop:
*buffer++ = '\0';
But this is the result:
printf("Working on line: '%s' %d\n", line, strlen(line));
Outputs: Working on line: 'test' 4
But by the end of the function the buffer is:
*buffer++ = '\0';
printf("Buffer at the very end: '%s' %d\n", buffer, strlen(buffer));
Outputs: Buffer at the very end: 'test' 7
So the output is showing that the string is getting messed up. What's the best way to build this string character by character? Are my string manipulations correct?
Any help would be much appreciated!
Thanks!