结构中的char指针 [英] char pointer in a structure

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

问题描述

  #include   <   stdio.h  >  
struct 示例
{
char * name;
};
int main()
{
struct 样本山姆;
sam.name =( char *)malloc( sizeof char )* 100 );
strcpy(sam.name, vicky);
printf( %d \ n的sizeof (sam.name));
return 0 ;
}





名称大小显示4



但我已分配100个字节,但它显示4个字节

解决方案

打印结果是正确的。 char指针的大小在你的机器上是4个字节。



如果你想打印数组的大小 name 指针指向:遗憾的是,这不能作为指向数组的指针的信息。 name 只是一个指向char类型元素数组的指针,你的代码必须分别记住该数组的长度。



如果您想要打印该数组中以空值终止的字符串的长度,您可以使用:

 printf( %d \ n,strlen(sam.name)); 


每当你在指针上运行sizeof运算符时,你只得到指针的大小,即在windows的情况下为4个字节。

如果你真的想要获得分配内存的大小,你需要遵循不同的方法,

在Windows平台上你有内存分配API,HeapAlloc,HeapFree和Heapsize。

所以不使用新的你可以使用HeapAlloc,请参考MSDN以获取有关参数的更多详细信息。

然后你可以使用Heapsize来获得为该内存位置分配的实际字节数。



http: //msdn.microsoft.com/en-us/library/windows/desktop/aa366599(v=vs.85).aspx [ ^ ]


sam.name 指针 char 的大小指针变量是4.您是否打算获得字符串的大小? ( strlen的(sam.name))。


#include <stdio.h>
struct sample
{
    char *name ;
};
int main()
{
    struct sample sam;
    sam.name = (char *)malloc(sizeof(char)*100);
    strcpy(sam.name,"vicky");
    printf("%d\n",sizeof(sam.name));
    return 0;
}



size of name is showing 4

but i have allocated 100 bytes but it is showing 4 bytes

解决方案

The printed result is correct. The size of a char pointer is 4 bytes on your machine.

If you wanted to print the size of the array the the name pointer is pointing to: That is unfortunately not available as information on a pointer to an array. name is just a pointer to an array of elements of type char and your code has to remember separately how long that array is.

In case you wanted to print how long the null-terminated string in that array is, you would use:

printf ("%d\n", strlen (sam.name));


whenever you run sizeof operator on pointers you get only the size of the pointer i.e 4 bytes in case of windows.
if you really want to get the size of allocated memory you need to follow different approach,
on windows platform you have memory allocation APIs, HeapAlloc, HeapFree and Heapsize.
so instead of using new you can use HeapAlloc, refer MSDN for further details on parameters.
then you can use Heapsize to get actual no of bytes allocated for that memory location.

http://msdn.microsoft.com/en-us/library/windows/desktop/aa366599(v=vs.85).aspx[^]


sam.name is a pointer to char and, the size of the pointer variable is 4. Did you intend to get the size of the string? (strlen(sam.name)).


这篇关于结构中的char指针的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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