This might sound a bit dumb but am confused.
I know the strlen() would return the size of the character array in c. But there is something different going on with pointers to character.
This is my code:
void xyz(char *number)
{
int i = 0;
int length = strlen(number) - 2;
while(i <= length)
{
printf("Number[]: %c",number[i]);
i++;
}
}
This prints the entire number I enter (Eg: 12345) but if I remove the -2 the result is not the same.
Could anyone tell me what am I missing?
There’s a good chance that you’re doing this to a string that you have obtained with
fgetsor a similar input function. In that case, it may well have the newline at the end still.If you change your code temporarily to:
that should also show the numeric codes for all characters.
The problem with encoding something like that
- 2in your function is that it will not work with:since it will stop early, printing out only
12. The caller should be calling with valid data, meaning that it should adjust the value to be a numeric string before calling.You can see this happening in the following program:
The (annoted) output of this, if you enter
98765, is:If you’re looking for a robust user input function that gets around this problem (and avoids dangerous things like unbounded
scanf("%s")andgets), I have one elsewhere on SO (right HERE, in fact) drawn from my arsenal.