-5

I'm trying to print a linked list of characters, and then later make a function to copy the string onto a new one and then reverse it and print it out. I'm confused as to why this is printing out only integers, and also how to reverse the string. Here is my code:

 #include<stdlib.h>
 #include<stdio.h>

 struct list_el 
 {
 char val;
 struct list_el * next;
 };


typedef struct list_el item;


int main() 

{
 item * curr, * head;
 int i;

 head = NULL;

 for(i='i';i>='a';i--) 
 {


  curr = (item *)malloc(sizeof(item));
  curr->val = i;
  curr->next  = head;
  head = curr;
 }



 head = NULL;


 while(curr) 
 {
  printf("%d\n", curr->val);
  curr = curr->next ;
 }

 return 0; 
}

3 Answers3

1

%d only prints numeric values by definition. If you want other content to be printed, use a different format string (such as %c).

Better, don't use printf() at all, but consider using something simpler (putc()?)

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
0

You need to use %c to print characters with printf. %d is for printing integers.

For more information about printf format strings, visit the Wikipedia article about this.

aglasser
  • 3,059
  • 3
  • 13
  • 10
0

To print the character represented by val use "%c".
To print the numeric value represented by val, use "%d".

char, short, int, unsigned, etc. are all integer types with various ranges.

When code use a format directive like "%d",%x or "%c" with printf() to print one of these types, different results are appropriate and different output occurs. Note: parameters after the format go though usual type promotions.

// Example assuming ASCII encoding
char a = 'A';
printf("%c\n", a);            // prints A
printf("%d\n", a);            // prints 65
printf("%x\n", (unsigned) a); // prints 41

There are additional issues to consider too, especially for long and long long, but this is a starter.

Community
  • 1
  • 1
chux - Reinstate Monica
  • 143,097
  • 13
  • 135
  • 256