c - 双指针和字符

标签 c pointers char

我的 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/

相关文章:

c - 如何在C程序中获取当前目录?

c++ - 用于检查 MySQL 连接性和 InnoDB 插件的 C/C++ 程序

c++ - 将字符串从 char 指针复制到 char 指针

c - 显示指针减法

使用数组的 Java 基于字符的队列

c - 使用 OpenMP : Parallel reduction calculation is invalid 时出错

c - 在读入时为 char 指针数组分配内存

c - 在不知道大小的情况下打印数组

c - 如何从 C 中的函数返回字符数组?

C - char* 列表 - 内存分配