0

Possible Duplicate:
C -> sizeof string is always 8

I found the following way to create a string:

#include <stdio.h>
#include <string.h>

int main(void) {
    char *ptr = "this is a short string";
    int count = sizeof ptr / sizeof ptr[0];
    int count2 = strlen(ptr);
    printf("the size of array is %d\n", count);
    printf("the size of array is %d\n", count2);
    return 0;
}

I can't use the the usual way to get the length by sizeof ptr / sizeof ptr[0], Does this way to create string is valid? Any pros and cons about his notation?

Community
  • 1
  • 1
mko
  • 21,334
  • 49
  • 130
  • 191

4 Answers4

2

When you do this

char *ptr = "this is a short string";

ptr is actually a pointer on the stack. Which points to string literal on the readonly memory.

[ptr] ---->  "This is a short string"

So trying to get the sizeof ptr will always evaluate to size of int on that particular machine.

But when you try this

char ptr[]="this is a short string";

Then actually for whole string the memory is created on the stack with ptr having starting address of the array

|t|h|i|s| |i|s| | |a| |s|h|o|r|t| |s|t|r|i|n|g|\0|

|' '| ==> this is atually a byte shown in above diagram and ptr keep the address of |t|.

So size of ptr will give you the size of whole array.

Omkant
  • 9,018
  • 8
  • 39
  • 59
1

Yes, using strlen to get the size of a string is valid. Even more, strlen is the proper way to get the size of a string. The sizeof solution here is even wrong. sizeof ptr will return 8 on 64 bits system because it is the size of a pointer, divided by the size of a char, which is 1, you will obtain only 8.

The only case where you can use sizeof to get the size of a string is when it is declared as an array of character (char[]).

tomahh
  • 13,441
  • 3
  • 49
  • 70
1

Because ptr is a pointer and not an array. If you used char ptr[] instead of char *ptr, you would have gotten an almost-correct result - instead of 22, it would have resulted in 23, since the size of the array incorporates the terminating NUL byte also, which is not counted by strlen().

By the way, "creating" a string like this is (almost) valid, but if you don't use a character array, the compiler will initialize the pointer with the address of an array of constant strings, so you should really write

`const char *ptr`

instead of what you have now (i. e. add the const qualifier).

0

This code will crash if you modify the string (because recent compilers see it as a constant). Besides, it gives incorrect results as sizeof(ptr) returns the pointer size rather than the string size.

You should rather write:

char ptr[] = "this is a short string";

Because this code will let you find the sctring length as well as modify the string contents.

Gil
  • 3,279
  • 1
  • 15
  • 25