0

Lets say I have two string sizes sizeA and SizeB, can I use them both to create an array like the following:

    char str[sizeA+sizeB];

I want the array to be one dimensional and with size of both sizeA and sizeB combined. How would I do that correctly?

Thank you!

2
  • 1
    Show the declaration of sizeA and sizeB. Commented May 23, 2014 at 14:03
  • Is that array definition inside a code block, making the array local? Then, if the compiler/library supports it alloca may be your best bet (given typical string lengths). Commented May 23, 2014 at 14:27

2 Answers 2

2

Yes, that's fine.

It's called a variable-length array and was added in C99.

If you intend to create an actual string in that array, you need to + 1 for the terminator.

If this is inside a function and you intend to return the new array, you must use heap allocation through malloc().

Sign up to request clarification or add additional context in comments.

Comments

1

If you use a compiler that does not support C99, and sizeA and sizeB are not constant, you can not do that. You could either determine a size that will be big enough for all cases, or you can dynamically allocate the buffer with the correct size using malloc

Comments

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.