What is the output of this C program with int pointers?

  • #1
diredragon
323
15

Homework Statement


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.

Homework Equations


3. The Attempt at a Solution [/B]
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']++;
       n++;
       //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 can't seem to grasp why.
       //how does it do it?
   }
   for(c = a; *c; printf("%c", *c++ + 'a'));
   printf("\n");
   free(a); free(b);
}
 
Last edited:
Physics news on Phys.org
  • #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.
 
  • Like
Likes diredragon
  • #3
willem2 said:
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.
Thanks, i understand that know :)
 

Similar threads

Replies
7
Views
2K
Replies
3
Views
974
Replies
3
Views
1K
Replies
2
Views
2K
Replies
12
Views
2K
Replies
11
Views
2K
Back
Top