1. Limited time only! Sign up for a free 30min personal tutor trial with Chegg Tutors
    Dismiss Notice
Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Homework Help: C program with int pointers

  1. Jun 11, 2017 #1


    User Avatar
    Gold Member

    1. The problem statement, all variables and given/known data
    I am supposed to analyze the code and find it's output without running it. Some things were unclear so i did run it and i have some things that puzzle me.
    2. Relevant equations
    3. The attempt at a solution

    Code (C):

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    enum e {N1=5, N2, N3, N4};

    void main() {
       char *a, *b, *c, i, j;
       int n = 0;
       a = (int*)calloc(N2, sizeof(char));
       b = c = (int*)malloc(N4 + 1);
       strcpy(b, "31131402");

       //not sure what happens in the next few lines.
       //a is an int pointer allocated to 6 char places.
       while (*c) {
           a[*c++ - '0']++;
           //first itteration *c = '3'
           //a['3' - '0'] = 0 because it's post increment
           //second itteration *c = '1'
           //a['1'-'0'] = 1
           //third itteration *c = '1'
           //debugger gives a[*c++ - '0'] as 1 again?
           //third itteration gives a[*c++ - '0'] = 1 and fourth a[*c++-'0']=0;
           //how to it assign them like this? It has something to do that it's int pointer with 6 char places but i cant seem to grasp why.
           //how does it do it?
       for(c = a; *c; printf("%c", *c++ + 'a'));
       free(a); free(b);
    Last edited: Jun 11, 2017
  2. jcsd
  3. Jun 11, 2017 #2
    a, b and c are defined as pointers to char. Even if your compiler accepts a = (int *) calloc( ... ), a will be a pointer to char and the cast won't do anything.
    The while loop just scans the string "31131402" using the pointer to character c, until the ascii zero at the end of the string is reached.
    a[*c++] is not the same as a[*c++ - '0']. '0' is subtracted from *c to convert the chars '0' .. '9 with ascii codes 48..57 to the ints 0..9.
    Using a['0'] should cause a crash.
  4. Jun 11, 2017 #3


    User Avatar
    Gold Member

    Thanks, i understand that know :)
Share this great discussion with others via Reddit, Google+, Twitter, or Facebook

Have something to add?
Draft saved Draft deleted