我有一个char数组文本,想要将字母数字小写值存储在指针数组中。即mystr应该指向“50sometexthere”的char []
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++;
}
我做错了什么?
答案 0 :(得分:2)
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
答案 1 :(得分:2)
函数tolower
返回一个整数,你错误地将它强制转换为char *
。
执行此操作的最佳方法是将源数组中的字母数字字符复制到目标数组
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.
如果您真的想使用strcpy
,则需要将目标字符串初始化为空字符串,并将字符复制为字符数组的一部分,并将该数组附加到目标字符串:
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++;
}
答案 2 :(得分:0)
您的错误是strcat调用中的强制转换。
几乎总是在C
中投射错误
strcat
需要2个指向char的指针,你提供了一个指向char和int的指针(错误地转换为指向char的指针)。