[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 890
  • Last Modified:

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.
0
purejamie
Asked:
purejamie
1 Solution
 
imladrisCommented:
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

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now