I am learning C and I am trying to get a toy example working. My fake use case is given a string of chars where each char represents and int, loop over each char of the string and convert it to an int. What I've tried so far has not worked.
EDIT: Original question edited to now include a main()
to allow responders to compile and using strtol
per suggestions in comments.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
char *charNums = "12345";
int num, num2, num3, i, n = strlen(charNums);
char *ptr = charNums;
for (i = 0; i < n; i++) {
num = atoi(&charNums[i]);
num2 = atoi(ptr);
num3 = strtol(ptr, NULL, 10);
printf("\ncharNums[%d] = %c (the expected value but as an int not a char)\n num = %d\n num2 = %d\n num3 = %d\n",
i, charNums[i], num, num2, num3);
ptr++;
}
return 0;
)
Edit: Show method of compiling of C code along with program execution
gcc -o soQuestion main.c
./soQuestion
charNums[0] = 1 (the expected value but as an int not a char)
num = 12345
num2 = 12345
num3 = 12345
charNums[1] = 2 (the expected value but as an int not a char)
num = 2345
num2 = 2345
num3 = 2345
charNums[2] = 3 (the expected value but as an int not a char)
num = 345
num2 = 345
num3 = 345
charNums[3] = 4 (the expected value but as an int not a char)
num = 45
num2 = 45
num3 = 45
charNums[4] = 5 (the expected value but as an int not a char)
num = 5
num2 = 5
num3 = 5
Appreciate any feedback.
Edit: The desired outcome of this program is to convert each char in the chars string "12345" to individual ints of 1 2 3 4 5 so I can do math with them such as sum them 1 + 2 + 3 + 4 + 5 = 15