我的 set_ccs 函数有问题。我无法从用户那里获取元素。我该如何解决这个问题?
int main(){
char *ccs;
*ccs =(char*)malloc(sizeof(char) * 80);//i have to use dynamic memory allocation
printf("Enter CCS: ");
set_ccs(&ccs);
free(ccs);
return 0;
}
int set_ccs(char **ccs){
int i = 0;
scanf("%s",*ccs);//Is it better to use fgets? Because scanf seems to count 'enter'
while(*ccs!='\0'){
ccs++;
i++;
}
printf("Length of sequence : %d\n",i);//It always return 3
printf("%s",ccs); //with weird elements
return i;
}
已经谢谢了。
最佳答案
除了展开答案之外,您应该使用
char *ccs;
ccs = malloc(80);
您应该使函数 set_ccs()
接受一个指针:
int set_ccs(char *ccs)
并从你的 main 中这样调用它:
set_ccs(css);
然后在您的函数中,您可以像这样使用 scanf()
:
scanf("%s", css);
现在,如果您想检查 '\0'
,最好在使用之前将“字符串”初始化为 0
。您可以使用 calloc(80)
而不是 malloc(80)
来实现这一点。
如果您需要指向指针的指针(char **ccs
),则必须在 main 中创建一个双指针,请检查以下代码:
int main(){
char *ccs;
char **ccs2; //a pointer to a pointer
ccs = calloc(80); //i have to use dynamic memory allocation
ccs2 = &ccs; //pass the address of the pointer to the double pointer
printf("Enter CCS: ");
set_ccs(ccs2); //pass the double pointer
free(ccs);
return 0;
}
int set_ccs(char **ccs){
int i = 0;
scanf("%s", *ccs);
char *c = *ccs; //copy to make increments
while(*c != '\0'){
c++;
i++;
}
printf("Length of sequence : %d\n", i);
printf("%s", *ccs);
return i;
}
关于c - 双指针和字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36737498/