Getting pointer data size

I tried the following code to find out how to get the size of the pointer data:

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

 int main(){
  char *test_char_ptr = "This is just a test";
  int *test_int_ptr = (int *) malloc(16*sizeof(int));
  for(int i = 0; i<16; i++){
    test_int_ptr[i] = i;
  }
  printf("%s\n",test_char_ptr);
  printf("Test char 1: %d\n", (int)sizeof test_char_ptr );
  printf("Test char 2:%d\n", (int)sizeof *test_char_ptr );
  printf("Test char 3: %d\n", (int)((strlen(test_char_ptr)+1) * sizeof(char)));
  printf("Test int 1:%d\n", (int)sizeof test_int_ptr );
  printf("Test int 2:%d\n", (int)sizeof *test_int_ptr );
  return EXIT_SUCCESS;
 }

And the code output (On 32 bit gcc 4.3):

This is just a test
Test char 1: 4
Test char 2:1
Test char 3: 20
Test int 1:4
Test int 2:4

I thought that sizeof (* test_char_ptr) would give me the size of the data inside * test_char_ptr. But instead, he gave me 1, which I think is sizeof char instead of data. The same goes for test_int_ptr. In short, my question is how can I get sizeof data inside a allocated array with a pointer or dynamic memory.

+5
source share
5 answers

, C, . , - , . , , - .

, strlen() - , , ('\0'); strlen(string) + 1.

+13

sizeof , . , 4 32-, 8 64- .

, , . , .

+5

, (), . , : malloc() , .

. .

+5

. "", .

, . Symbian AllocSize(ptr).

+3

A pointer only indicates where the data begins. He knows nothing about the size of the data.

+2
source

All Articles