[英]Strlen printing the wrong length of an array
所以,我正在开发一个从 CSV 文件中获取信息的程序。
我正在尝试使用strlen
获取该 CSV 文件中字符串的长度,但它始终返回相同的值,而且该值是错误的。
typedef struct User{
// id login type created_at followers follower_list following following_list public_gists public_repos
int id, followers, following, public_gists, public_repos;
char* login;
char* type;
char* created_at;
int* following_list;
int* follower_list;
} *Users;
int main(){
FILE *fp = fopen("users.csv", "r");
if(!fp){
printf("Erro");
return 0;
}
char *str;
char p[25];
str = (char *) malloc(200000);
Users new = (Users) malloc (sizeof (struct User));
Users pointer = new;
int x = 0;
while(fgets (str, 200000, fp) != NULL){
char *tmp = strdup(str);
char *token;
char **sp = &tmp;
sp = &tmp;
while((token = strsep(sp, ";"))){
switch(x){
case 0:
pointer->id = atoi(token);
break;
case 1:
pointer->login = token;
break;
case 2:
pointer->type = token;
break;
case 3:
pointer->created_at = token;
break;
case 4:
pointer->followers = atoi(token);
break;
case 5:
pointer->follower_list = atoi(token);
break;
case 6:
pointer->following = atoi(token);
break;
case 7:
pointer->following_list = atoi(token);
break;
case 8:
pointer->public_gists = atoi(token);
break;
case 9:
pointer->public_repos = atoi(token);
break;
}
x++;
printf("%s ", token);
}
printf("Length: %ld", strlen(pointer->login));
int x = 0;
putchar('\n');
}
free(str);
free(pointer);
fclose(fp);
return 0;
}
输出:
28980885 hanjuin User 2017-05-26 11:47:56 0 [] 0 [] 0 2
Length: 5
我不知道是我愚蠢还是我的代码有问题。
我可以绝对向您保证的一件事是 strlen() 工作正常,并准确返回它应该返回的内容。
代码中对 strlen() 的唯一调用传递了它从函数 strsep() 获得的参数,该函数不是标准库函数,因此我会在那里寻找问题所在。 也许它返回的字符串中有一些额外的空格? 或者,在解析字符串和获取其长度的时间之间,字符串正在通过指针进行修改?
抛出一些 printf() 来看看发生了什么,或者学习使用调试器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.