Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C编程局部字符指针_C_String_Pointers_Char_Malloc - Fatal编程技术网

C编程局部字符指针

C编程局部字符指针,c,string,pointers,char,malloc,C,String,Pointers,Char,Malloc,我有一个函数,它返回前n个字符,直到到达指定的字符为止。我想传递一个ptr,设置为字符串中的下一个单词;我如何做到这一点?这是我目前的代码 char* extract_word(char* ptrToNext, char* line, char parseChar) // gets a substring from line till a space is found // POST: word is returned as the first n characters read until p

我有一个函数,它返回前n个字符,直到到达指定的字符为止。我想传递一个ptr,设置为字符串中的下一个单词;我如何做到这一点?这是我目前的代码

char* extract_word(char* ptrToNext, char* line, char parseChar)
// gets a substring from line till a space is found
// POST: word is returned as the first n characters read until parseChar occurs in line
//      FCTVAL == a ptr to the next word in line
{
   int i = 0;
   while(line[i] != parseChar && line[i] != '\0' && line[i] != '\n')
   {
      i++;
   }

   printf("line + i + 1: %c\n", *(line + i + 1));  //testing and debugging

   ptrToNext = (line + i + 1);    // HELP ME WITH THIS! I know when the function returns
                                  //   ptrToNext will have a garbage value because local
                                  //   variables are declared on the stack

   char* temp = malloc(i + 1);

   for(int j = 0; j < i; j++)
   {
      temp[j] = line[j];
   }
   temp[i+1] = '\0';

   char* word = strdup(temp);
   return word;
}
char*extract\u单词(char*ptrToNext,char*line,char-parseChar)
//从第行获取子字符串,直到找到空格为止
//POST:word作为读取的前n个字符返回,直到第行出现parseChar
//FCTVAL==行中下一个单词的ptr
{
int i=0;
而(行[i]!=parseChar和行[i]!='\0'和行[i]!='\n')
{
i++;
}
printf(“行+i+1:%c\n”,*(行+i+1));//测试和调试
ptrToNext=(line+i+1);//请帮助我!我知道函数何时返回
//ptrToNext将有一个垃圾值,因为本地
//变量在堆栈上声明
char*temp=malloc(i+1);
对于(int j=0;j
您将传递一个指向char的指针的参数;然后在函数中,可以更改指向指针的值。换句话说

char * line = ...;
char * next;
char * word = extract_word(&next, line, 'q');
在你的功能中

// Note that "*" -- we're dereferencing ptrToNext so
// we set the value of the pointed-to pointer.
*ptrToNext = (line + i + 1);

有一些库函数可以帮助您解决此类问题,strspn()strcspn()非常方便

#include <stdlib.h>
#include <string.h>

char *getword(char *src, char parsechar)
{

char *result;
size_t len;
char needle[3] = "\n\n" ;

needle[1] = parsechar;
len = strcspn(src, needle);

result = malloc (1+len);
if (! result) return NULL;
memcpy(result, str, len);
result[len] = 0;
return result;
}
#包括
#包括
char*getword(char*src,char-parsechar)
{
字符*结果;
尺寸透镜;
字符指针[3]=“\n\n”;
针[1]=parsechar;
len=strcspn(src,针);
结果=malloc(1+len);
如果(!result)返回NULL;
memcpy(结果、str、len);
结果[len]=0;
返回结果;
}

word
驻留在堆栈上,但不是由
word
指向的数据。