0

The issue that I am having is that I am trying to build a DLL. And I am using char instead of strings to store information.

I have defined the following in the header file:

class Test{
public:
    int qLenght;
    char firstName[];
    char surName[];
};

I am having problems inputting codes from the main program using the following:

int main()
{

        Test theTest;
        theTest.firstName[0] = {"Mike Smith","Jonny Vegas","Jimmy Woo"};

}

I have included the header code at the top of my main project.

It won't let me add to the char array. This may seem like a stupid question but I am struggling and hopefully someone can shed some light as to where I am going wrong. Am I missing a parameter?

0

1 Answer 1

1

Your class needs to know how much memory to allocate when you instantiate the class (which is not the same time as you assign the values).

class Test
{
public:
    char firstName[2][100];
};

int main()
{
    Test theTest;
    strcpy(theTest.firstName[0], "Mike Smith");
    strcpy(theTest.firstName[1], "Jonny Vegas");
    return 0;
}

Alternatively, you can allocate memory for the strings dynamically at the time of assignment, but then you need to remember to free it again:

class Test{
public:
    char *firstName[2];
};

int main()
{
    Test theTest;
    theTest.firstName[0] = strdup("Mike Smith");
    theTest.firstName[1] = strdup("Jonny Vegas");

    // do stuff

    free(theTest.firstName[0]);
    free(theTest.firstName[1]);
    return 0;
}
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you Vandhunden. Well explained and make sense. Thank you.
Hi Vandhunden, Sorry will not let me upvote as I am new to this and don't have enough reputation to upvote. Sorry!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.