c - Linux C 数组长度问题

标签 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");
  }
}

最佳答案

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

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

关于c - Linux C 数组长度问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21648282/

相关文章:

java - 通过将字符串拆分为条件子字符串来获取java数组

c - 如何在 C 中手动将环境值设置为整数零

c - 为什么 mode_t 使用 4 字节?

c - Windows API 有滚动条控件吗?

c++ - 使用 stat 检测文件是否存在(慢?)

c++ - 评估 gdb 中的变量/函数

ruby-on-rails - 将制表符分隔的 CSV 文件解析为 Ruby 2.0 中的哈希数组

c - 数据库程序: array type has incomplete element type

Java运行环境还是其他问题?

linux - Rsync 复制未更改的文件(USB 驱动器、FAT32)