2

I see in c++ programming language some recommendations like "don't use char in struct type",

struct Student{
    int stdnum, FieldCode, age;
    double average, marks, res[NumOfCourses];
    char Fname[20], Lname[20], cmp[20];
};

And is better to use:

struct Student{
    int stdnum, FieldCode, age;
    double average, marks, res[NumOfCourses];
    string Fname, Lname, cmp;
};

Any other recommendations would be welcome on the matter

Thank you in advance

Matt
  • 17,290
  • 7
  • 57
  • 71
MLSC
  • 5,872
  • 8
  • 55
  • 89
  • 1
    You'll notice when it comes to implement proper manipulations and operations on the raw `char` array members! – πάντα ῥεῖ Feb 05 '14 at 10:18
  • 1
    Can you link to *any* recommendation to use `string` in C? I doubt you'll find that, that only makes sense for C++. –  Feb 05 '14 at 10:18
  • yes you are right..I am going to remove c tag..thank you – MLSC Feb 05 '14 at 10:19
  • It is not only about `char`, it is about using fixed size arrays to hold data that does not necessarily match their length. – juanchopanza Feb 05 '14 at 10:21
  • It's also not just "in struct types" - you should prefer `std::string` to an array of `char`s in general. – Joseph Mansfield Feb 05 '14 at 10:22
  • I don't think it has anything to do with structs, strings are simply more convenient and less error-prone. That said, I just needed the opposite in my code - my struct is memcpy'ed later on, and embedding the string inside is much simpler. – Code Painters Feb 05 '14 at 10:22
  • This is probably not anything to do with `char` actually but more to do with the difficulty in getting correctness with built in array types. For example, you should probably also swap out your double array for vector E.g. use `vector res` You basically get everything of the built in array type but with extra safety. Same goes for `string` which is just a nice array of characters – Brandin Feb 05 '14 at 10:24
  • @Brandin: the size of the res member (NumOfCourses) is a compile time constant, so it's presumably a fixed size that's always appropriate. Unless it's a "it'll never get bigger than this" assumption, of course ;) – Carl Colijn Feb 05 '14 at 10:26

4 Answers4

8

Because string handling using C-level raw character arrays is hard to get right, prone to fail, and when it fail it can fail rather horribly.

With a higher-level string datatype, your code becomes easier to write, more likely to be correct. It's also often easier to get shorter code, since the string datatype does a lot of work for you that you otherwise have to do yourself.

The original question was tagged with the tag, but of course string is a construct so this answer doesn't apply to C. In C, you can choose to use some string library (glib's GString is nice) to gain similar benefits but of course you'll never have overloaded operators like in C++.

unwind
  • 391,730
  • 64
  • 469
  • 606
3

@unwind's answer is generally perfectly appropriate, unless it's really a sequence of 20 char's you're after. In that case a std::string might be overkill (performance-wise as well), but a std::array might still be better.

Carl Colijn
  • 1,423
  • 9
  • 29
  • @MortezaLSC sometimes you want to store an array of bytes of a compile-time known length, as opposed to null-terminated strings of run-time determined size. – juanchopanza Feb 05 '14 at 10:24
  • To make it more concrete: like when you want to store 20 grades, all being a single letter A to F. Then a char array of fixed size 20 is perfectly adequate with no overhead. Then requirements change and it's not always 20, and there you'll need to draw a line and start using std::string to make life easier for yourself. – Carl Colijn Feb 05 '14 at 10:28
2

For your student class, you have first name, last name and "cmp" - I've no idea what that's supposed to be. Clearly a student could have a first and/or last name longer than 20 characters, so by hardcoding an array of 20 elements you've already created a system that:

  • has to bother to check all inputs to make sure no attempt is made to store more than 19 characters (leaving space for a NUL), and
  • can't reliably print out any formal documents (e.g. graduation certificates) that require students' exact names.

If you don't carefully check all your input handling when modifying arrays, your program could crash, corrupt data and/or malfunction.

With std::string, you can generally just let people type into whatever fields your User Interface has, or pick up data from files, databases or the network, and store whatever you're given, print whatever you're given, add extra characters to it without worrying about crossing that threshold etc.. In extreme situations where you can't trust your input sources (e.g. accepting student data over untrusted network connections) you may still want to do some length and content checks, but you'd very rarely find it necessary to let those proliferate throughout all your code the way array-bounds checking often needs to.

There are some performance implications:

  • fixed length arrays have to be sized to your "worst supported case" size, so may waste considerable space for average content
  • strings have some extra data members, and if the textual content is larger than any internal Short String Optimisation buffer, then they may use further dynamic memory allocation (i.e. new[]), and the allocation routines might allocate more memory than you actually asked for, or be unable to effectively reuse delete[]d memory due to fragmentation
  • if a std::string implementation happens to share a buffer between std::string objects that are copied (just until one is or might be modified), then std::strings could reduce your memory usage when there are multiple copies of the student struct - but this probably only happens transiently and is only likely to help with very long strings

It's hard to conclude much from just reading about all these factors - if you care about potential performance impact in your application, you should always benchmark with your actual data and usage.

Separately, std::string is intuitive to use, supporting operators like +, +=, ==, !=, < etc., so you're more likely to be able to write correct, concise code that's easily understood and maintained.

Tony Delroy
  • 102,968
  • 15
  • 177
  • 252
1

I dont think it makes difference in C as well.

Check this precious stackoverflow answer explained clearly states strings are more secure than char *.

Community
  • 1
  • 1
Sunil Bojanapally
  • 12,528
  • 4
  • 33
  • 46