Copying alhpanumeric chars in C
I have a char array of text, want to store the alphanumeric lowercase value in a pointer array. ie mystr should 开发者_开发百科point to a char[] of "50sometexthere"
char[] myline = " 50 Some Text Here ";
char *mystr = (char *)malloc(128 * sizeof(char));
char *tmp = myline;
while (*tmp != '\0'){
if (isalnum(*tmp))
strcat(mystr,(char*) tolower(*tmp));
tmp++;
}
What am I doing wrong?
char *myline = " 50 Some Text Here ";
char *mystr = (char *)malloc(128); //sizeof char is always 1
char *tmp = myline;
char *tmpdest = mystr;
while (*tmp != '\0'){
if (isalnum(*tmp))
*tmpdest++ = tolower(*tmp); //this line is changed!
tmp++;
}
*tmpdest = '\0';
HTH
The function tolower
returns an integer and you are wrongly casting it to char *
.
The best way to do this is to copy alphanumeric characters from the source array into the destination array
char myline[] = " 50 Some Text Here "; // put the [] after the variable.
char *mystr = malloc(128);
char *tmp = myline;
char *destPtr = mystr;
while (*tmp != '\0'){
if (isalnum(*tmp)) {
*destPtr++ = *tmp;
}
tmp++;
}
*destPtr = 0; // terminating nul character.
If you really want to use strcpy
, you need to initialize your destination string to an empty string and make the character to be copied part of a character array and append that array to the destination string:
char myline[] = " 50 Some Text Here "; // put the [] after the variable.
char *mystr = malloc(128);
char *tmp = myline;
mystr[0] = 0; // initialize the destination string.
while (*tmp != '\0'){
char str[2] = {0}; // temp string of size 2.
if (isalnum(*tmp))
str[0] = tolower(*tmp); // put the char to be copied into str.
strcat(mystr,str); // append.
tmp++;
}
Your error is the cast in the strcat call.
almost always a cast, in C
, is wrong
strcat
takes 2 pointers to char, you're supplying a pointer to char and an int (wrongly cast to pointer to char).
精彩评论