【发布时间】:2014-09-09 19:45:43
【问题描述】:
我正在编写一个不使用 strtok() 的字符串标记器。这主要是为了我自己的改进和对指针的更多理解。我想我几乎拥有它,但我一直收到以下错误:
myToc.c:25 warning: assignment makes integer from pointer without a cast
myToc.c:35 (same as above)
myToc.c:44 error: invalid type argument of 'unary *' (have 'int')
我正在做的是遍历发送到方法的字符串,找到每个分隔符,并将其替换为“\0”。 “ptr”数组应该有指向分离子串的指针。这是我目前所拥有的。
#include <string.h>
void myToc(char * str){
int spcCount = 0;
int ptrIndex = 0;
int n = strlen(str);
for(int i = 0; i < n; i++){
if(i != 0 && str[i] == ' ' && str[i-1] != ' '){
spcCount++;
}
}
//Pointer array; +1 for \0 character, +1 for one word more than number of spaces
int *ptr = (int *) calloc(spcCount+2, sizeof(char));
ptr[spcCount+1] = '\0';
//Used to differentiate separating spaces from unnecessary ones
char temp;
for(int j = 0; j < n; j++){
if(j == 0){
/*Line 25*/ ptr[ptrIndex] = &str[j];
temp = str[j];
ptrIndex++;
}
else{
if(str[j] == ' '){
temp = str[j];
str[j] = '\0';
}
else if(str[j] != ' ' && str[j] != '\0' && temp == ' '){
/*Line 35*/ ptr[ptrIndex] = &str[j];
temp = str[j];
ptrIndex++;
}
}
}
int k = 0;
while(ptr[k] != '\0'){
/*Line 44*/ printf("%s \n", *ptr[k]);
k++;
}
}
我可以看到错误发生在哪里,但我不确定如何纠正它们。我该怎么办?我是正确分配内存还是只是我如何指定地址的问题?
【问题讨论】: