Why am I getting random numbers when I try to increase the ascii value of a char?

StackOverflow https://stackoverflow.com/questions/23667423

  •  22-07-2023
  •  | 
  •  

Domanda

int n = argv[i][j];
n = n + (int)argv[1]; 

/* I'm pretty sure the above part that is wrong. What I was hoping that this 
would do is take the number the person put in and increase n by that number but 
it isnt working*/ 

printf("%d\n", n);
  • i = the string numbers of the argument
  • j = the characters of the string

What I want is to make it so when someone types ./123 12 hi I want it to increase the ascii characters of h and i by 12 or whatever number they put in. When I test my code out with

./123 1 hi 

I get an output of

-1081510229
-1081510228

instead of

105
106 

which is i and j, the next letters of h and i

Libraries I'm using

stdio.h 
studio50.h
string.h
È stato utile?

Soluzione

argv[1] is a string (i.e, a null-terminated char array), casting it to int doesn't give the result you expected

You should use atoi to do the job. Or better, use strtol to get better stability.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top