-1
char* varc = "ALICE";
char varl[] = "ALICE";
char* vars = (char*)calloc(6,sizeof(char));
strcpy(vars,"ALICE");

Which of the above definitions should I use more?

D M
  • 5,769
  • 4
  • 12
  • 27
devst1
  • 27
  • 2

1 Answers1

4
char* varc = "ALICE";

This is a pointer to a CONSTANT (fixed) string, you cannot change the characters, so it should be:

const char* varc = "ALICE";

char varl[] = "ALICE";

This text can be changed after declaration, but it has a fixed size of 6-bytes.


char* vars = (char*)calloc(6,sizeof(char));
strcpy(vars,"ALICE");

With this one, you can choose the size of the buffer before putting any text in it, and you can over-allocate space if you might later want to put a longer string ("SAMANTHA") in it.

Overall, do not think in terms of "which one should I use more?".

Think in terms of "What are the limitations and abilities of each technique, and which one is correct for this specific use-case"

abelenky
  • 63,815
  • 23
  • 109
  • 159