获取一个指针的数据的大小 [英] Getting the size of the data of a Pointer

查看:785
本文介绍了获取一个指针的数据的大小的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试以下code,以了解如何获取一个指针的数据的大小:

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\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;
 }

和code的输出(在32位GCC 4.3):

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

我认为的sizeof(* test_char_ptr)会给我* test_char_ptr内的sizeof的数据。而是它给了我1,我认为这是焦炭的sizeof,而不是数据。同样对于test_int_ptr。长话短说,我的问题是我怎样才能得到一个指针或动态分配的内存阵列内的sizeof数据。

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.

推荐答案

这不是你可以在C做不维护自己的信息。您所创建的阵列,所以你在一个点就知道它们的大小,你只需要跟踪它在你自己的。你可以精心打造一个数据结构来帮助你,或者只是保持阵列和大小信息,而无需任何数据结构都没有。

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.

此外,您的code使用的strlen()来获得字符串的大小 - 确保你记住,返回的规模将不包括终止空字符('\\ 0');字符串常量的内存大小为的strlen(字符串)+ 1

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.

这篇关于获取一个指针的数据的大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆