I wonder if there is a way to initialize a string array to a value I decide on during memory allocation, so it won't contain any garbage and the null character will be placed at the correct place. I know that using calloc the memory allocated is initialized to all zeros, but in this case involving strings it doesn't help.
I practice using pointers and allocation memory in C. There is an exercise in which I wrote a function for copying a string to another string - In main(), I allocate memory using malloc for both strings based on the strings lengths the user provides, and then the user enters the first string. At this point I send the pointer of the first string and second string (uninitialized) as parameters to strCopy(char* str1, char* str2). Inside that function I also use another basic function I wrote, to calculate the length of a string. but as you may guess, since the second string is full of garbage, it's length calculation inside the function is messed up.
void strCopy(char* str1, char* str2)
{
int str1len = str_len(str1); // basic length calculating function
int str2len = str_len(str2);
int i;
for (i = 0; i < str2len; i++)
{
str2[i] = str1[i];
}
str2[i] = '\0';
if (str2len < str1len)
printf("There wasn't enought space to copy the entire string. %s was
copied.\n", str2);
else
printf("The string %s has been copied.\n", str2);
}
Right now it works fine when initializing str2 in a loop in main(), but I am interested in other possible solutions.
Thank you very much for any help!