I have an array of strings that has been read from a file.
At some point i need to take one element out, add * before and * after and put it back to the same array.
So far I’ve managed to add one asterisk at the end with strcat. And it is printing it out correctly.
Now, how do I add the one at the beginning?
//malloc for the array has been done when read from file
char **array;
int arraySize;
for (i=0;i<arraySize;i++){
if (some_condition){
//Add * chars
array[i]=strcat(array[i],"*");
printf("Element %s was marked",array[i]);
}
//prints for example *foo*
}
Sorry if the question is completely stupid and the answer might be obvious. Thanks for any possible answers in advance!
UPD: array malloc function
void readd(FILE *file){
size=0; /*local size */
char line[BUFSIZ]; /* Local array for a single word read */
while ((fgets(line,sizeof(line),file))!=NULL){
/* trim newline char */
if (line[strlen(line)-1]=='\n')
line[strlen(line)-1] = '\0';
array=(char**)realloc(array,(size+1)*sizeof(char *));
array[size++]=strdup(line);
}
}
If the original
array[i]elements have enough room for the additional characters:Edit: Since you’ve updated your question, I’ll update my answer. 🙂
First, be advised that it’s dangerous to use
realloc()like this:If the
realloc()fails, thenarrayis reassigned toNULLand the original pointer is lost, orphaning the memory that had been allocated to it. This is safer:Of course, if you’ll be doing this often, you might as well keep track of the current size and allocate room for another hundred or thousand elements at a time.
Since the individual strings are allocated with
strdup()you have two options:Allocate an extra 2 characters for each, in case you need to add the asterisks. This isn’t unreasonable unless there are millions of strings, or the system is memory-constrained.
Reallocate each string before adding the asterisks, using code like the snippets above.