【问题标题】:C programming local character pointersC 编程本地字符指针
【发布时间】:2012-02-25 05:59:17
【问题描述】:

我有一个函数,它返回前 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;
}

【问题讨论】:

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

标签: c string pointers char malloc


【解决方案1】:

你将传递一个参数,它是一个 指向 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);

【讨论】:

    【解决方案2】:

    有一些库函数可以帮助您解决此类问题。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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-17
      • 1970-01-01
      • 2012-04-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-28
      相关资源
      最近更新 更多