Sizeof char * array in C / C ++

There are many similar queries, but in my case, I donโ€™t understand what is not working:

int mysize = 0;
mysize = sizeof(samplestring) / sizeof(*samplestring);
std::cout << mysize << '\n' << samplestring;

It is output:

4

Press 'q' to quit.

How is this possible? 4 is definitely not the size of this line. I even tried the following, with the same result:

mysize = sizeof(samplestring) / sizeof(samplestring[0]);

EDIT: Ok, this announcement:

char *samplestring = "Start."; 

I am in C ++, but I need to use functions that accept only char *. Later in the code, I assign new lines to this variable, for example:

samplestring = "Press 'r' for red text.";

Yes, the compiler gives me warnings, but I have no idea how I can use different lines if I can not overwrite them ...

+5
source share
6 answers

4is not a row size because it is samplestringnot a row. This is a char*whose size (on your platform) is 4 divided by 1 (size char), correctly, 4.

++ std::string length().

C strlen, char NULL.

+13

, . , , - .

char samplestring[] = "hello";
char * samplestring = "hello";

, , . 32- 4 , .. , 4 .

, .

mysize = strlen(samplestring);
+4

, sizeof(samplestring[0]) sizeof(*samplestring), samplestring. , , samplestring , sizeof(char) 1.

, samplestring. :

char const *samplestring = "Hello, World!";

char *samplestring = malloc( ... );

char samplestring[10];

samplestring char *, sizeof(samplestring) sizeof(char *), 4.

samplestring char[10] ( 10 ), , char * , char , . sizeof - .

, , ( ).

#include <stdio.h>

void foo( char (*arr)[42] )
{
  printf( "%u", (unsigned)sizeof(*arr) );
}

int main()
{
  char arr[42];
  foo( &arr );

  return 0;
}  

:

42

, , . - ( strlen, NULL).

+4

, , . , , :

size_t size(char * p) { // p is a pointer
    return sizeof(p) / sizeof(*p); // size of pointer
}

size_t size(char p[]) { // p is also a pointer        
    return sizeof(p) / sizeof(*p); // size of pointer
}

, sizeof (char) == 1, ; , .

++ (, , C) :

template <typename T, size_t N>
size_t size(T (&)[N]) {
    return N;  // size of array
}

, std::vector std::string, .

C strlen, , .

+1

char. , , 32- .

++, std::string:

std::string samplestring("Hello world");
std::cout << samplestring.size() << std::endl;
0

sizeof , . , , โ€‹โ€‹-

samplestring[4]

4. , , , ,

strlen(samplestring);

( )

0

All Articles