Sizeof () & array name and pointer

Source: Internet
Author: User

In sizeof function compute, the start address of the array and the pointer to the array are different.

#include <stdio.h>int love(char *p){    printf("sizeof(p) is:%d ", sizeof(p));    return 0;}int main(){    char a[100];    char *l = a;    printf("\nsizeof(a) is:%d and sizeof(l) is:%d \n",sizeof(a), sizeof(l));    love(a);}

Result: sizeof (a) is: 100 and sizeof (l) is: 8

Sizeof (P) is: 8

 

Therefore, in some subfunctions, do not expect to obtain the array size by pointing to the pointer to the first address of the array. The following is an occasional error:

int send_osd_message(char* ip_addr, int port, char * message)  {CACHE_PRINT("\n%s line:%d start ...\n", __func__, __LINE__);int socket_descriptor; int iter=0;struct sockaddr_in address;assert(sendlen);memset(&address, 0, sizeof(address));address.sin_family=AF_INET;address.sin_addr.s_addr=inet_addr(ip_addr);address.sin_port=htons(port);socket_descriptor=socket(AF_INET,SOCK_DGRAM,IPPROTO_UDP);sendto(socket_descriptor,message, sizeof(message),0,(struct sockaddr *)&address,sizeof(address));close(socket_descriptor);CACHE_PRINT("\nMessage is sent to osd:%s\n", ip_addr);return 0;}

 

In this case, even if the message points to a larger array, only 8 bytes of data can be sent on 64-bit machines.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.