Please diagnose my pointer problem

Discussion in 'Mac Programming' started by orangezorki, Jun 5, 2014.

  1. orangezorki macrumors 6502a

    Joined:
    Aug 30, 2006
    #1
    Dear all,

    I'm writing a program for a project that revolves around the need to dynamically allocate a big chunk of memory. But for whatever reason, and despite much searching, reading the relevant chapters in the books I have, I am still unable to do something as easy as setting the value of a char in the memory allocated. For example:

    Code:
    int main(int argc, const char * argv[])
    {
    
        unsigned char* ptr;
        
        ptr = calloc(1000, sizeof(char));
        
        *ptr  = 0;
        *(ptr+1) = 1;
        *(ptr + 2) = 2;
        *(ptr + 3) = 3;
        
        printf("%c" , *(ptr + 2) );
        
        return 0;
    }
    
    
    This prints an upside down question mark - not what I expected!

    Any ideas on what stupid thing I'm doing?

    Many thanks,

    David
     
  2. subsonix macrumors 68040

    Joined:
    Feb 2, 2008
    #2
    Use %d instead of %c. %c prints the variable as a character mapping to ascii, ascii values in that region are not printable characters:

    Code:
         The decimal set:
    
           0 nul    1 soh    2 stx    3 etx    4 eot    5 enq    6 ack    7 bel
           8 bs     9 ht    10 nl    11 vt    12 np    13 cr    14 so    15 si
    
    Edit:

    If you actually intend to use characters, you need to enclose the values in single quotes:

    Code:
        *ptr  = '0';
        *(ptr+1) = '1';
        *(ptr + 2) = '2';
        *(ptr + 3) = '3';
        
        printf("%c" , *(ptr + 2) );
    
     
  3. chown33 macrumors 604

    Joined:
    Aug 9, 2009
    #3
    First, what did you expect?

    You've stored the binary value 2 at *(ptr+2). You're printing this value with the %c format, which will output it as a single character. Look up the ASCII character code for that value.

    If you wanted it to print as the numeric string "2", then don't use %c.


    Second, you can subscript the pointer, like this:
    Code:
        ptr[0]  = 0;
        ptr[1] = 1;
        ptr[2] = 2;
        ptr[3] = 3;
    
    This is a universal rule in C: pointers can always be subscripted. It's not limited to just calloc'ed memory.
     
  4. orangezorki thread starter macrumors 6502a

    Joined:
    Aug 30, 2006
    #4
    Thank you so much - I said it would be a stupid mistake!

    I do want to store just a value in the char, and had tried ptr [2] = 2; but did it the long way to try and work out the problem.

    David
     

Share This Page