bsteo
bsteo

Reputation: 1779

Linux C array length issue

I have the following code, PCRE match some string then stores the results into an array to have them unique. The problem is I make some mistake because instead getting back 7 unique strings I get only one. What am I doing wrong?

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

Upvotes: 0

Views: 103

Answers (1)

timrau
timrau

Reputation: 23058

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

Since stored_ is a pointer to pointer instead of an array, sizeof(stored_) equals to sizeof(stored_[0]). You need other ways (such as the last value of i) to decide how many elements were allocated in stored_.

Upvotes: 4

Related Questions