Reputation: 39
I just started to learn C language. My code finds the short forms of alphabet (a-z or A-Z) or numbers (0-9) in a string and then expands it (abcd..z, etc).
But I encountered a problem- Some strange symbols are added in the end of string. Could you please help me to figure this out?
To see code and result: http://codepad.org/4sfBZv48
Code:
#include <stdio.h>
#include <stdlib.h>
int main()
{
char str[16] = "--g-6hA-Za-z56-9";
char exstr[127];
int lasti = 0;
int i;
int j;
int start;
for(i = 0; str[i] != 0; i++){
if(str[i] > 64 && str[i] < 91 && str[i+1] == '-' && str[i+2] > 64 && str[i+2] < 91){
}else if(str[i] > 96 && str[i] < 123 && str[i+1] == '-' && str[i+2] > 98 && str[i+2] < 123){
}else if(str[i] > 47 && str[i] < 58 && str[i+1] == '-' && str[i+2] > 47 && str[i+2] < 58){
}else{
exstr[lasti++] = str[i];
continue;
}
start = i;
i += 2;
for(j = str[start]; j <= str[i]; j++)
exstr[lasti++] = j;
}
printf("%s\n",exstr);
return 0;
}
Upvotes: 0
Views: 123
Reputation: 15175
In C strings are null terminated.
Read more about it here on wikipedia
So you need to leave a space at the end for the zero terminator.
char str[17] = "--g-6hA-Za-z56-9"; /* here the compiler is so kind to insert the null terminator for you */
or as Quentin suggested let the compiler figure it all out by itself
char str[] = "--g-6hA-Za-z56-9"; /* here the compiler is so kind to insert the null terminator for you and figure out the length */
Upvotes: 2
Reputation: 172
As others have answered, you didn't leave room for the null terminator to be placed as the last element in str
What ends up happening as a result is you continue your for loop iteration past "the end" (or rather what you expected to be the end) of str since str[i] doesn't equal 0
The iteration will continue until you just happen to reach memory that will satisfy the condition of your for loop which was supposed to check for the end of str (signified by the null termination)
Upvotes: 0
Reputation: 2833
You need to leave a space for a terminator in your string - here you define it to be char[16], then put 16 chars in locations 0..15, so there is no room for the null terminator that you then check for.
If you define as char[17] you should be OK
Upvotes: 2