1

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!

liooshine
  • 105
  • 6

2 Answers2

1

No, there is not. You have to manually initialize it.

If you want to copy a string while allocating memory, you can use strdup. Note that this is a POSIX function, which means this will only work on POSIX-compliant operating systems, Windows, and any other OSs that implement it.

S.S. Anne
  • 15,171
  • 8
  • 38
  • 76
0

Well, for this particular situation you can use memcpy. A simple way could be like this in your code instead of the for loop:

memcpy(str2, str1, str2len);

But your code is seriously flawed. I don't know how you have implemented str_len but there is absolutely no way (if you're not using non-standard, non-portable, dirty hacks) to get the size of the block that a pointer is pointing to.

klutt
  • 30,332
  • 17
  • 55
  • 95