unsized array declaration

So I copied a code exactly from the book here is the snipet where the problem is:

1
2
3
4
5
6
7
8
int main(int nNumberofArgs, char* pszArgs[])
{
	cout << "This program concatenates two strings\n(this version may crash.)" << endl;
	char szStrBuffer[256];
	char szString1[];
	strncpy(szString1, "This is a string", 16);
	char szString2[];
	strncpy(szString2, "THIS IS A STRING", 16);



The compiler(Microsoft Visual) gives me "error C2133: 'szString1' : unknown size"

I know that declaring an arbitrary size fixes the problem but why can't I just declare the string without a size like in the book?
The compiler must know the size of an array, either explicitly int array[5]; or implicitly int array[]={1,2,3,4,5};
Its implicitly defined in line 6, no?
The size must be known in the declaration of the array furthermore, the compiler doesn't know what strncpy does and it wouldn't be executed at compile time anyway
it should be done on declaration char szString1[256];
Use strings not char[]. No size issues in sight.
And what's up with those arguments for main? Are those valid? (I suppose that the names are not forced; it just has to be int and char** types.)
Use strings not char[]. No size issues in sight.


+1

Whatever book OP is reading is apparently lame.

(I suppose that the names are not forced; it just has to be int and char** types.)


They are valid. They're usually namced 'argc' and 'argv', but the types are right (int,char**)
I thought so. It would really make no sense to force the names to be something, not to mention that that would be effectively un-enforceable.
Also, although strings are superior to char[] in pretty much every way (the only disadvantage being that char[] is primitive while you need includes to get <string>), most books should at least cover them to explain their use and their glaring weaknesses (array size declaration I'm talking about you).
Strings would be perfect if they could somehow be a primitive type. But that kind of defeats the purpose of it being a class.
I wouldn't say std::string is perfect. I have many beefs with it, actually.

But it's certainly better than char arrays for variable length string representation.
strings do common task for you. it's not that bad.

Strings would be perfect if they could somehow be a primitive type.
i wish that could happen...
I don't see why it matters whether or not they're a primitive type. It's a standard lib... so you won't ever be in a situation where you can't use it.

Is putting a single #include in your file such an ordeal?
Meh. code bloat.
I don't think I'd like C++ as much if std::string was a built-in type. It'd be too abstract for the kind of work the language is expected to perform.

EDIT: ^Quiet, you.
Last edited on
code bloat.


How do you figure?

std::string functions are likely as small or smaller than their C string counterparts.

Unused functions don't add anything.

etc
Topic archived. No new replies allowed.