• C

Explain this line of code!? : sprintf(buffer, "%d", argv[1][strlen(argv[1])-1]);

Hi experts,

I am pulling apart some old c code at work and have come accross a line I have litle idea about, hopefully it will be completely obvious to you guys.

The line is this:

sprintf(buffer, "%d", argv[1][strlen(argv[1])-1]);

The value of argv[1] is UK12398
Buffer evaluates to 56

I can't see how buffer evaluates to 56, can someone explain to me exactly the process that it goes through to get that number from UK12398

Many Thanks in advance
Jamie.
purejamieAsked:
Who is Participating?
 
imladrisConnect With a Mentor Commented:
argv[1] is a pointer to the string "UK12398"

strlen(argv[1]) is the length of the string "UK12398": 7.

So argv[1][strlen(argv[1])-1] will resolve to argv[1][6] which is the character 8.

A character is represented by the number of its ASCII encoding, which for '8' is decimal 56.

So sprintf "prints" the decimal value in buffer.
0
 
purejamieAuthor Commented:
Capital! Many Thanks.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.