C编程:如何从变量类型char **访问单个字符

时间:2018-02-07 04:02:26

标签: c

我有一个主要用于测试,通过一个简单的句子作为测试。

    int main()
{
   char *sentence = "Hello There."; /* test sentence */
   char *word;  /* pointer to a word */

  printf( "sentence = \"%s\"\n", sentence );  /* show the sentence */

  word = get_word( &sentence );  /* this will allocate memory for a word */

  printf( "word = \"%s\"; sentence = \"%s\"\n", word, sentence );  /* 
  print out to see what's happening */

  free(word);  /* free the memory that was allocated in get_word */

  return 0;
}

这是我的get_word函数,它需要char **作为传递参数,并且必须输出指针。

char *get_word( char **string_ptr )
{
    char *word;
    word = (char*)malloc(919 * sizeof(char)); /* Assign memory space for storying gathered characters */
    strcpy(word,"")  /***********This is the line I need help with****/ 

  return word;
}

这是一个学校项目的作业问题,所以不能要求太多,我主要担心的是我想弄清楚如何将主要句子中的第一个字符“H”传递给内部的变量词我的get_word函数。由于此功能是作业的一部分,我无法更改签名。

还有更多的问题,比如大写和小写之间的排序,但我想如果我理解这个概念,我应该能够做其余的事。

感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

在评论中,我问道:

  

您想传递单个字符'H'还是指向它的指针?如果要传递单个字符,则需要查看strcpy()的签名 - 将单个字符作为第二个参数传递将是错误的。您对取消引用指针了解多少?

回应是:

  

我对解除引用有点了解。它基本上从指针中收集一个值?如果我使用代码strcpy(word, *string_ptr);,我可以将字符串的整个值复制到变量字。

     

我需要能够传递一个角色;问题要求我循环遍历整个字符串,直到达到非字母字符,将任何大写字母转换为小写,然后返回单个单词。然后我将再次为字符串中的下一组字母字符执行此操作。

我注意到了:

  

正确 - strcpy(word, *string_ptr)会将字符串"Hello world"复制到数组word中。如果您只想从字符串中复制一个字符,请考虑strncpy(),但不要忘记对结果字符串进行空终止。看起来您需要更新*string_ptr中的值以允许复制到返回函数的字符 - 这就是为什么它需要是char **而不仅仅是char * }。

但是,根据要求,最好不要使用strcpy()strncpy()

你可以使用H甚至是(*string_ptr)[0]来到**string_ptr,但是使用指针的数组符号相当笨拙地经常输入(不止一次?)。如果(*string_ptr)中的指针是空指针 - 或者无效,则它们都容易崩溃;但是,下面的代码也是如此。如果您愿意,可以与assert(*string_ptr != NULL);核对,并且您包括<assert.h>,无论您选择哪种其他错误处理。

有很多选择,但我可能会使用一个变体:

char *src = *string_ptr;   /* Starting position */
char *dst = word;
int c;

while (*src != '\0')
{
    int c = (unsigned char)*src++;
    …break on space or other characters as required…
    …map c as required…
    *dst++ = c;
}
*dst = '\0';  /* Null terminate the string */
*string_ptr = src;
return word;

这避免了各种各样的问题。使用本地指针src(源字符串 - 匹配dst,目标字符串)避免必须始终写入(*string_ptr)。使用c准备好将值传递给<ctype.h>的函数(宏)。演员(unsigned char)处理 当普通char类型被签名时,单字节代码集中的重音字符(当普通char类型未签名时无害)。循环中的增量可以避免超出字符串的末尾。