gpt4 book ai didi

c - 将字符串作为指针传递给函数

转载 作者:行者123 更新时间:2023-11-30 18:41:31 25 4
gpt4 key购买 nike

对于许多人来说,这是一个简单的函数,但作为初学者,我还没有克服指针幽灵,特别是在涉及字符串时。我了解 strcmp、strcpy、strlen 的一些示例以及如何使用 NULL 终止符在内存中分配字符。我想我也明白了内存中的指针变量如何指向 int var 或 char 等的地址,并且通过将它们取消引用到 var/char 来分配它们,但是每当我尝试编写代码时,指针幽灵就会出现回来咬我。所以,我在这里尝试运行它,但不起作用。如果您能为我澄清这一点,我将不胜感激......

//GETNAME function should return a string that is not NULL and less than 20 characters

char getname (char *s1)
{
int i, n;
char s2[i];
printf ("Enter your name:" );
scanf ("%s", "s2");

if (s2 == NULL)
return 0;

else if(n<20)

for ( i=0, n =strlen (s2 + 1); i<n; i++)

*(s1+i) = s2[i]; //copy characters from s2 and point to chars of s1

return *s1;
}

int main (int argc, char *argv[])

{
char name[20];
char urname;

urname = getname(name);

printf (" Your name is : %s\n", urname);

getch();

return NULL;
}

最佳答案

这里有几个错误;可能还有更多:

  1. 未初始化的变量:

    int i, n;
    char s2[i];

    i 此处未初始化,但您可以像初始化一样使用它。 i 应该具有什么值?像这样,这是未定义的行为。

  2. scanf 的参数不正确:

    scanf ("%s", "s2");

    第二个参数应该是指向要写入输入的内存的指针,而不是常量字符串。应该是:

    scanf ("%s", s2);
  3. strlen 的参数不正确:

    for ( i=0, n =strlen (s2 + 1); i<n; i++)

    您想要将 1 添加到字符串长度而不是字符串本身,所以它应该是

    for ( i=0, n = strlen(s2) + 1; i<n; i++)
  4. getname 的一般问题,包括返回类型:

    char getname (char *s1)

    为什么这个函数这么复杂?您可以直接scanf进入参数s1。您不需要 s2 来做任何事情。而且返回类型也是错误的。您返回一个指针,而不是单个char。应该是:

    char* getname(char *s1)
  5. 未正确处理 getname 的返回值:

    char urname;
    urname = getname(name);

    getname 返回一个指向 char 的指针,而不是单个 char。应该是:

    char* urname;
    urname = getname(name);

关于c - 将字符串作为指针传递给函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21067518/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com