我这里有一个用于测试的主要内容,它通过一个简单的句子作为测试。
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;
}
这是一个学校项目的作业问题,所以不能要求太多,我主要关心的是我想弄清楚如何将 main 中句子的第一个字符“H”传递给其中的变量单词我的 get_word 函数。由于此函数是作业的一部分,因此我无法更改签名。
这个问题还有更多内容,比如大写和小写之间的排序,但我想如果我理解这个概念,我应该能够完成剩下的事情。
感谢您的帮助。
最佳答案
在评论中,我问:
Do you want to pass the single character
'H'
, or a pointer to it? If you want to pass a single character, you need to review the signature ofstrcpy()
— it would be a mistake to pass a single character as the second argument. What do you know about dereferencing pointers?
对此的回应是:
I know a little bit about dereferencing. It basically gathers a value from a pointer? If I use the code
strcpy(word, *string_ptr);
, I can copy the entire value of the string to the variable word.I need to be able to pass a single character; the question requires me to loop over the entire string until a non-letter character is reached, convert any uppercase letters to lowercase and then return a single word. then I'll have to do this again for the next set of letter characters in the string.
我注意到:
Right —
strcpy(word, *string_ptr)
will copy the string"Hello world"
into the arrayword
. And if you only want to copy one character from a string, considerstrncpy()
, but don't forget to null-terminate the result string. It looks like you're going to need to update the value in*string_ptr
to allow for the characters copied to the return function — that's why it needs to be achar **
and not just achar *
.
但是,考虑到要求,最好不要使用 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
类型无符号时是无害的)。循环中的增量避免超出字符串末尾。
关于C编程: How to Access a Single Character from variable Type char**,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48655797/