views:

51

answers:

3

Hey, this should be pretty simple but getting stuck.

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?

+2  A: 
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

Armen Tsirunyan
Thanks, this works great. Need to get my head round these pointers, as I sort of see whats happening
Igor K
A: 

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).

pmg
How would i convert to lowercase though without returning an integer?
Igor K
@Igor K: as you see from Armen's answer, you don't use the integer for string functions. You need to find another way (his way is pretty good).
pmg
+2  A: 

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++;
}
codaddict
Thank you for explaining that, makes sense.
Igor K
If you are going to use this approach in real code, you will want to ensure that you don't overrun the allocated 128 bytes at `mystr`.
Tim
@Tim will do, thanks!
Igor K