Linux C阵列长度问题

时间:2014-02-08 16:05:06

标签: c arrays linux

我有以下代码,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");
  }
}

1 个答案:

答案 0 :(得分:4)

size_t length = sizeof(stored_) / sizeof(stored_[0]);

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