3

I'm a beginner programmer in C so excuse me if my language/style is not professional.

Question: I'm trying to determine the size of a character array, so that I can later on know the size to allocate using malloc().

My code:

char *dest;

char *src1 = "Test String";
char src2[] = "Testing!";

dest = (char *) malloc( sizeof(src1) );

The problem is I want to determine the size in memory of src1 and src2. i.e. size of src1 should be 11, and size of src2 should be 8. But the results I have received from sizeof() are:

  • sizeof(*src1) is 1 since that the sizeof(char)
  • sizeof(src1) is 4 <-- I don't know why can someone explain please?
  • sizeof(src2) is 9 <-- I'm guessing this is what I want and the null terminator counts into the size as well

But then how to properly determine size of src1? and how come sizeof(src2) works but sizeof(src1) doesn't?

If I'm unclear in what I'm trying to do, please reply and I'll try to make it clearer.

Thanks in advance.

Splaty
  • 604
  • 1
  • 8
  • 21

3 Answers3

3

sizeof returns the size of the type you pass to it. as src1 is a pointer, it return 4.

If you are only working with string, simply use strlen(src1) to get the size of your string. Your allocation line should then look something like

dest = (char*) malloc(strlen(src1) + 1); // add one for the \0
tomahh
  • 13,441
  • 3
  • 49
  • 70
2
sizeof(src1)

gives you the size of an pointer on your environment and not length of the array.From your results size of the pointer on your environment is 4.
You need to use strlen if you want to determine size of the string literal pointed by an pointer as in case of src1.

sizeof(src2) 

returns size of the character array.

In order to understand the difference between the two, You should understand:

What is the difference between char a[] = “string”; and char *p = “string”;

Community
  • 1
  • 1
Alok Save
  • 202,538
  • 53
  • 430
  • 533
1

If you want the length of the string (which is what it seems from the numbers you provide), you can use the strlen(char *) function. (The strlen function is part of <string.h>)

Just pass in your string like so:

int len1 = strlen(src1); // This will give 8 as intended
Suhail Patel
  • 13,644
  • 2
  • 44
  • 49