Getting the size of the data of a Pointer

前端 未结 5 666
借酒劲吻你
借酒劲吻你 2020-12-10 06:52

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

 #include 
 #include 
 #include 

        
相关标签:
5条回答
  • 2020-12-10 07:41

    The pointer doesn't keep track of the number of objects that are allocated behind the (first) one it points to. That's because it can't: malloc() just returns the address of the first element, nothing else.

    Therefor there's no way to find out the size of a dynamically allocated array. You have to keep track of it for yourself.

    0 讨论(0)
  • 2020-12-10 07:44

    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 ('\0'); the in-memory size of a string constant is strlen(string) + 1.

    0 讨论(0)
  • 2020-12-10 07:53

    There is no standard way to do this. You have to keep the length of the allocated memory in another variable, or use a 'container' that keeps track for you.

    Some platforms do have functions for finding the number of bytes in an allocation, e.g. Symbian as an AllocSize(ptr) function.

    0 讨论(0)
  • 2020-12-10 07:55

    sizeof only knows the full size of the array if that's statically known at compile time. For a pointer, it will return the size of the memory address, i.e. 4 on 32-bit, 8 on 64-bit.

    When you use pointers, it's up to you to know and keep track of the size of the data it points to. The language implementation won't do it for you like it would for arrays.

    0 讨论(0)
  • 2020-12-10 07:57

    A pointer only points to where the data begins. It doesn't know anything about the size of the data.

    0 讨论(0)
提交回复
热议问题