【问题标题】:Linux C array length issueLinux C数组长度问题
【发布时间】:2014-02-08 16:05:06
【问题描述】:

我有以下代码,PCRE 匹配一些字符串,然后将结果存储到一个数组中以使其唯一。问题是我犯了一些错误,因为取回 7 唯一字符串我只得到一个。我做错了什么?

#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <pcre.h>

int main() {
  pcre *myregexp;
  const char *error;
  int erroroffset;
  int offsetcount;
  int offsets[(0+1)*3]; // (max_capturing_groups+1)*3
  const char *result;
  char **stored_ = NULL;
  int i;
  char *subject = "9,5,6,3,2,5,6,3,2,5,6,3,2,2,2,2,2,2,2,5,5,5,5,5,0,5,5,5,5,6,6,6,6,6,6,1,";
  myregexp = pcre_compile("\\d,", PCRE_MULTILINE|PCRE_DOTALL|PCRE_NEWLINE_ANYCRLF, &error, &erroroffset, NULL);
  if (myregexp != NULL) {
    offsetcount = pcre_exec(myregexp, NULL, subject, strlen(subject), 0, 0, offsets, (0+1)*3);
    i = 0;
    while (offsetcount > 0) {
        // match offset = offsets[0];
        // match length = offsets[1] - offsets[0];
        if (pcre_get_substring(subject, offsets, offsetcount, 0, &result) >= 0) {
          //printf("%s\n", result);
          stored_ =  realloc(stored_, sizeof(char*) * (i + 1));
          stored_[i] = malloc(strlen(result) + 1);
          strcpy (stored_[i], result);
          i++;
        }
        offsetcount = pcre_exec(myregexp, NULL, subject, strlen(subject), offsets[1], 0, offsets, (0+1)*3);
    }
    size_t length = sizeof(stored_) / sizeof(stored_[0]);
    for (i = 0; i < length; i++) {
      printf("inside: %s\n",stored_[i]);
    }
    for (i = 0; i < 10; i++) {
      free (stored_[i]);
    }
    free (stored_);
  } else {
      printf("Syntax error in REGEX at erroroffset\n");
  }
}

【问题讨论】:

标签: c arrays linux


【解决方案1】:
size_t length = sizeof(stored_) / sizeof(stored_[0]);

由于stored_指向指针的指针 而不是数组,因此sizeof(stored_) 等于sizeof(stored_[0])。您需要其他方式(例如 i 的最后一个值)来决定在 stored_ 中分配了多少元素。

【讨论】:

  • 知道pointer to pointer 是否可以独一无二(我指的是其中的元素)吗?
  • @xtmtrx 请详细说明您的问题,甚至提交一个新问题。我真的不明白你的意思。
  • 我的意思是在上面的例子中我想做的就是匹配一些字符串并让它们唯一(比如 1、2、3 而不是 1、2、3、3、1、1)为什么我想到了数组和指向指针的指针,然后在打印之前使元素唯一。
猜你喜欢
  • 1970-01-01
  • 2020-10-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-24
  • 1970-01-01
  • 1970-01-01
  • 2014-09-17
  • 2016-12-07
相关资源
最近更新 更多