繁体   English   中英

如何在C中使用char *

[英]How to use char * in C

我有这样的主要功能:

void main()
{
     char *s;
     inputString(s);
     printf("%s",s);

}

和inputString函数:

void inputString(char *&s)
{

    //Some code line to input a string and set s point to this string

}

是否有一个函数自动malloc内存足够输入的存储字符串(我需要在inputString函数中输入字符串)。

只需三行代码(将它们放入int main() )就足够了

std::string s;
std::cin >> s; //or getline() as desired
std::cout << s;

如果继续使用这种C风格的方法,那么否,您将不得不做一些假设并自己分配足够的内存。 C ++方法要优越得多,请使用std :: strings且不要手动分配:

#include <string>
#include <iostream>
void inputString(std::string& s)
{

    //Don't bother for the memory management

}
int main() 
{
     std::string s;
     inputString(s);
     std::cout << s ;
}

另请注意,您的代码不是合法的C ++。 void main()是非法的!

编辑:在此答案的时间问题被标记为C ++。 后来这个问题没有被OP重新标记,我不太同意...

您在示例中混合使用C和C ++。

在您可以使用s的情况下,应将其初始化。 例如,像这样:

void inputString(char *&s)
{
    s = strdup(xxx); // or malloc, calloc, etc.

}

但实际上,最好只使用普通的旧C:

char* inputString(void)
{
    char* s = strdup(xxx);
    return s;
}

假设您这样做是C而不是C ++。

有两种方法,无论是inputString必须分配存储器或呼叫者inputString必须分配的存储器。

如果inputString分配了内存,则您的函数可能类似于:

char* inputString(void)
{
    int len = strlen (MyInternalString) + 1;
    char* s = malloc (len);
    strncpy(s, MyInternalString, len);
    return s;
} //similar to what Rustram illustrated

您还应该包括:void freeString(char * str){free(str); }。 这使用户清楚需要他们自己管理返回的字符串的内存。

或者,您可以在需要用户提供所需内存的地方编写inputString。 然后看起来像

int inputString(char* str, int maxLen) //
{
  if (maxLen >= myInternalStringLength + 1)
  {
    strncpy(str, myInternalString, maxLen)

  }
  return myInternalStringLength  + 1;
}

在这里,我的字符串的用户可以检查返回代码,以查看他分配的缓冲区是否足够大。 如果它太小,那么他总是可以重新分配更大的一个

您的主要对象现在变为:

int main()
{
     char *s = NULL;
     int len = inputString(s, 0);
     s = alloca(len); //allocates the memory on the stack
     len = inputstring(s, len);
     printf("%s",s);
} //no need to free the memory because the memory alloca'ed gets 
  //freed at the end of the stack frame
int main()
{
    std::string s;
    inputString(s);
    printf("%s",s.c_str());  
}

和inputString函数:

void inputString(std::string& s)
{
    //Some code line to input a string and set s point to this string
    std::cin >> s;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM