Question

Right off the bat, I'm required to use dynamically allocated character arrays for my assignment, so do NOT suggest I just use strings. I need to create a method that accepts a character array as an argument, and inserts that character into a char* using strcpy. How do I do this without first initializing the char*?

Here is my code so far:

char* char_array;
char test_array[] = {'t','e','s','t','\0'};
strcpy(char_array, test_array);
Was it helpful?

Solution

Your char_array is just an unitialized pointer. You need to dynamically allocate memory for it and then carry out strcpy.

char* char_array = new char[6];
char test_array[] = {'t','e','s','t','\0'};
strcpy(char_array, test_array);

Or as suggested by Joachim you can use strdup() to duplicate a string - it will allocate the memory and copy the string into it.

In both cases, don't forget to free() (or delete[]) the resulting memory once you're done with it.

OTHER TIPS

You can't do that unless you actually allocate a chunk of memory for char_array through malloc or new.

int length = 6;
char* char_array = (char*) malloc(sizeof(char) * length);

or

char* char_array = new char[6];
char * char_array = NULL;
void yourFunc(char your_array[]) {
    if (NULL != char_array) {
        free(char_array);
        char_array = NULL;
    }
    char_array = (char *)malloc(sizeof(char) * strlen(your_array));
    strcpy(char_array, your_array);
}

you stated you need a method/function that accepts a char[]/char *
you have stated your constraints ...
this does seem to be low level for instructional purpose
I assuming null terminated character array and valid source character array

//function accepts character array
char * charseqduplicate(char * s)
{
    //low level c
    const int len = strlen(s) + 1;;
    char * copy = new char[len];
    strcpy(copy, s);
    //remember to delete or use something like unique_ptr
    return copy;

}

void letsdothis()
{
    //low level c
    char test[] = {'y','e','s',char(0)};
    char * dup = charseqduplicate(test);
    cout << dup;
    delete [] dup;

}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top