Thread: sizeof function and pointers

  1. #1
    Registered User
    Join Date
    Jan 2014
    Posts
    62

    sizeof function and pointers

    I have this simple program:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    
    static unsigned char cmd[]={
                    0x01,0x80,0x00,0x00,0x00
                 };
    
    
    void printCmd(unsigned char cmd[])
    {
    	int i;
    	
    	printf("size: %zu", sizeof(cmd));
    	for(i=0;i<5;i++)
    	{
    		printf("0x%x\n", cmd[i]);
    	}
    }
    
    
    int main(int argc, char *argv[])
    {
    	int i,n;
    	if ( argc != 2 )
    	{
    		printf("specify n sensors\n");
    		return 1;
    	}
    	n = atoi(*++argv);
    	
    	for(i=1; i<n+1;i++)
    	{	
    		//reset cmd to default
    		cmd[1] = 0x80; 
    		
    		cmd[1]|=i;
    		printCmd(cmd);
    		sleep(3);
    	}
    
    
    	return 0;
    }
    It gives this output:

    size: 80x1
    0x81
    0x0
    0x0
    0x0
    size: 80x1
    0x82
    0x0
    0x0
    0x0
    size: 80x1
    0x83
    0x0
    0x0
    0x0

    All is right except the size. Why does it give 80x1 as size instead of the digit 5?

  2. #2
    Registered User
    Join Date
    May 2010
    Posts
    4,632
    You can't use sizeof on an array in a different scope than where you actually defined the array. Remember when you pass the array to your function the array decays to a pointer to the first element.

    Also why are you using the global variable?

    Jim

  3. #3
    TEIAM - problem solved
    Join Date
    Apr 2012
    Location
    Melbourne Australia
    Posts
    1,907
    Code:
    unsigned char cmd[]
    // Is equal to
    unsigned char *cmd
    And what is the size of an unsigned pointer to a char?

    What you'll need is another parameter that passes the size of the array in the scope that the array is declared
    Code:
    void printCmd(unsigned char cmd[], size_t cmdSize);
    
    ...
    
    printCmd(cmd, sizeof(cmd));
    Fact - Beethoven wrote his first symphony in C

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Pointers in a function, sizeof doesn't get array length
    By ulillillia in forum C Programming
    Replies: 4
    Last Post: 01-27-2011, 11:36 AM
  2. Replies: 2
    Last Post: 06-06-2008, 10:10 AM
  3. sizeof function
    By chrismiceli in forum C Programming
    Replies: 10
    Last Post: 02-28-2004, 08:28 PM
  4. sizeof and pointers
    By XBOX War3z in forum C++ Programming
    Replies: 3
    Last Post: 11-21-2003, 05:24 AM
  5. SizeOf function
    By vanilly in forum C Programming
    Replies: 4
    Last Post: 02-13-2003, 12:18 PM