Reputation: 357
I'm trying to write some code that keeps adding words to a character array called sTable separated by \0. The final contents of sTable would look something like:
"word\0int\0paper\0mushroom\0etc\0"
My first thought would be to read the words into a separate character array , tempWord, and concatenate them together, however, how would I be able to add \0 between them and keep sTable ass the final array? I'm not very familiar with C, thank you in advance for the help!
Upvotes: 0
Views: 2075
Reputation: 21318
You can do this by keeping a pointer for the next location in the word array that should receive a word. The function add_word()
below takes a pointer to a location in an array of char
s and a string. After adding wrd
to the location beginning at next
, a pointer to the location following the null terminator is returned. The next
pointer is initially given the address of the first location in the character array words[]
. Keep in mind that there is no error checking here, so the caller is responsible for ensuring that the string will fit in the array.
#include <stdio.h>
#define MAX_SIZE 1000
char * add_word(char *next, const char *wrd);
int main(void)
{
char words[MAX_SIZE];
char *next = words;
next = add_word(next, "word");
next = add_word(next, "int");
next = add_word(next, "mushroom");
next = add_word(next, "etc");
for (char *ptr = words; ptr < next; ptr++) {
if (*ptr == '\0') {
printf("\\0");
} else {
putchar(*ptr);
}
}
putchar('\n');
return 0;
}
char * add_word(char *next, const char *wrd)
{
while (*wrd != '\0') {
*next++ = *wrd++;
}
*next++ = '\0';
return next;
}
Program output:
word\0int\0mushroom\0etc\0
Here is a version of the above program that has been modified so that the add_word()
function takes an index for the starting location of the word being added, and returns and index for the next word. An array, word_indices[]
has also been added to save the starting indices for each word added to words[]
.
#include <stdio.h>
#define MAX_SIZE 1000
size_t add_word(char *tokens, size_t next, const char *wrd);
int main(void)
{
char words[MAX_SIZE];
size_t word_indices[MAX_SIZE] = { 0 };
size_t next = 0, count = 0;
char *input[4] = { "word", "int", "mushroom", "etc" };
for (size_t i = 0; i < 4; i++) {
next = add_word(words, next, input[i]);
word_indices[++count] = next;
}
/* Show characters in words[] */
for (size_t i = 0; i < next; i++) {
if (words[i] == '\0') {
printf("\\0");
} else {
putchar(words[i]);
}
}
putchar('\n');
/* Print words in words[] */
for (size_t i = 0; i < count; i++) {
puts(&words[word_indices[i]]);
}
return 0;
}
size_t add_word(char *tokens, size_t next, const char *wrd)
{
while (*wrd != '\0') {
tokens[next++] = *wrd++;
}
tokens[next++] = '\0';
return next;
}
Program output:
word\0int\0mushroom\0etc\0
word
int
mushroom
etc
Upvotes: 2