Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
357 views
in Technique[技术] by (71.8m points)

c - Getting the size of the data of a Pointer

I tried the following code in order to see how to get size of the data of a pointer:

 #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
",test_char_ptr);
  printf("Test char 1: %d
", (int)sizeof test_char_ptr );
  printf("Test char 2:%d
", (int)sizeof *test_char_ptr );
  printf("Test char 3: %d
", (int)((strlen(test_char_ptr)+1) * sizeof(char)));
  printf("Test int 1:%d
", (int)sizeof test_int_ptr );
  printf("Test int 2:%d
", (int)sizeof *test_int_ptr );
  return EXIT_SUCCESS;
 }

And code's output is(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 sizeof the data inside of the *test_char_ptr. But instead it gave me 1 , which i think that is the sizeof char instead of the data. The same is for the test_int_ptr. Long story short, my question is how can i get the sizeof data inside a pointer or dynamically memory allocated array.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

That's not something you can do in C without maintaining the information yourself. You created the arrays, so you knew their sizes at one point, you just have to keep track of it on your own. You could create a data structure to help you, or just maintain the array and size information carefully without any data structure at all.

In addition, your code is using strlen() to get the size of the string - make sure you remember that the size returned will not include the terminating null character (''); the in-memory size of a string constant is strlen(string) + 1.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...