Man*_*son 1 c string methods pointers function
我仍然是C的新手.我仍然无法理解所有指针.我正在尝试创建一个返回String的方法.这是功能,它仍然不完整.
char getS(char *fileName){
FILE *src;
if((src = fopen(fileName, "r")) == NULL){
printf("%s %s %s", "Cannot open file ", fileName, ". The program is now ending.");
exit(-1);
}
char *get = " ";
//insert getting a random word here
return(*get);
}
Run Code Online (Sandbox Code Playgroud)
而我正试图像这样调用这个方法
char *article = getS("articles.txt");
char *noun = getS("nouns.txt");
char *verb = getS("verbs.txt");
Run Code Online (Sandbox Code Playgroud)
编译器给我这个:
error: invalid type argument of unary ‘*’ (have ‘int’)
Run Code Online (Sandbox Code Playgroud)
我该怎么办?
Kei*_*son 15
以下内容可能比您正在寻找的信息要多得多.现在不要太担心吸收它,但是你可能以后需要它.
首先,关于术语的重要说明.C没有"字符串"类型.引用ISO C标准:
甲串是由封端的字符的连续序列,并且包括第一个空字符.[...] 指向字符串的指针是指向其初始(最低寻址)字符的指针.
特别是,char*值是指针,而不是字符串(尽管我们通常使用char*指针来访问和操作字符串).即使数组本身也不是字符串,但它可以包含字符串.
对于(相对简单的)函数,char*您返回的值指向字符串文字的(第一个字符),因此内存管理不是问题.对于更复杂的情况,这种语言坦率地说并不是特别有用,你必须自己做一些工作来管理记忆.
函数可以轻松返回char*指向字符串的值,允许调用者使用该字符串执行它喜欢的操作 - 但组成该字符串的字符存储在哪里?
有(至少)三种常见方法.
(1)函数返回一个指向静态数组开头的指针char:
char *func(void) {
static char result[100];
// copy data into result
return result;
}
Run Code Online (Sandbox Code Playgroud)
这有效,但它有一些缺点.只有一个result数组副本,连续调用func()将破坏该数组的内容.并且阵列具有固定的大小; 它必须足够大才能容纳它能够返回的最大字符串.标准C asctime()函数以这种方式工作.
(2)调用者可以传入指向字符串的指针,并让函数填充它:
void func(char *buffer) {
// code to copy data into the array pointed to by buffer
}
Run Code Online (Sandbox Code Playgroud)
这给调用者带来了负担,调用者必须分配一个数组char,特别是必须知道它需要多大.
(3)该函数可以使用malloc()以下内容为字符串分配内存:
char *func(void) {
char *result = malloc(some_number);
if (result == NULL) {
// allocation failed, cope with the error
}
// copy data into the array pointed to by result
return result;
}
Run Code Online (Sandbox Code Playgroud)
这样做的好处是函数可以决定需要分配多少内存.但是调用者必须知道字符串是在堆上分配的,所以它可以稍后通过调用来释放它free().该malloc()和free()功能也可以是相对昂贵的(但除非你确定你的程序的性能不够好,不用担心这一点).
实际上,还有第四种方法,但这是错误的:
char *bad_func(void) {
char result[100];
// copy data into result
return result; // equivalent to "return &result[0];"
}
Run Code Online (Sandbox Code Playgroud)
这里的问题是result函数的局部问题,并没有定义为static,所以一旦函数返回,数组对象就不再存在.调用者将收到一个指向不再保留的内存的指针,并且可以在您的背后重复使用.您可以将指针返回给本地static对象(因为单拷贝存在的程序的生命周期),你可以返回值的本地非的static对象,但你不能安全返回的地址在本地的非static宾语.
该comp.lang.c常见问题是一个很好的资源.
Your function should return a char * (a string), instead of a char, and it should return the same. So the function becomes:
char * getS(char *fileName) {
FILE *src;
if((src = fopen(fileName, "r")) == NULL) {
printf("%s %s %s", "Cannot open file ", fileName, ". The program is now ending.");
exit(-1);
}
char *get = " ";
//insert getting a random word here
return get;
}
Run Code Online (Sandbox Code Playgroud)