:: Re: [DNG] Studying C as told. (For …
Pàgina inicial
Delete this message
Reply to this message
Autor: Edward Bartolo
Data:  
A: dng
Assumpte: Re: [DNG] Studying C as told. (For help)
Hi,

It seems the interest to give me feedback about what I am studying and
coding is dwindling rapidly. Nevertheless, I am coding a parser in C.
I have already coded the tokeniser and tested it. Next, I will
dedicate my efforts to the actual parsing. I am writing a syntax
checker for simple boolean expressions as an EXERCISE.

Thankfully, the world does have other people who are willing to
positively criticise and actually help me in my endeavour to REVISE C,
for I have already studied it some years ago.

I am attaching my little project code. (parser.c)

Edward
#include <stdio.h>
#include <ctype.h>
#include <stdlib.h>
#include <string.h>

#define token_delta 50

typedef char* pchar;
pchar* tokens;
int token_count = 0;

void tokenise(char* expression) {
  char ch;              /* character at iterator's position */
  char* atoken;         /* token to be added to token list  */
  char* start = NULL;   /* holds a char* to point to start of multicharacter token */
  char* string_token;   /* holds multicharacter token */
  int char_count = 0;   /* keeps track of number of characters in multicharacter token */


  int while_counter = 0;
  /* expr_len_and_null holds the total length of input string including null terminator */
  int expr_len_and_null = strlen(expression) + 1;
  while (while_counter++ <= expr_len_and_null) {
    ch = *expression++; 
    switch (ch) {
      case '(': 
      case ')':
      case '^':
      case 'v':
      case '!':
      case '\0':
        if (start && char_count > 0) {
          string_token = malloc((char_count + 1)*sizeof(char));
          strncpy(string_token, start, char_count);
          tokens[token_count++] = string_token;


          start = NULL;
          char_count = 0;
        }                


        if (ch == '\0') return;
        atoken = malloc(2*sizeof(char));
        atoken[0] = ch;
        atoken[1] = '\0';
        tokens[token_count++] = atoken;
        break;


      case '\n':
        break;  


      default:
        if (start == NULL)
          start = expression - 1;
        char_count++;  
    }
  }
}


void free_memory() {
int k = token_count;

while (--k >= 0) free(tokens[k]);
free(tokens);
}


int main() {
char input[101];

tokens = malloc(token_delta*sizeof(char*));
fgets(input, 100, stdin);
tokenise(input);

  int k = -1;
  printf("token count is %d\n", token_count);
  while(++k < token_count)
    printf("%s\n", tokens[k]);


free_memory();

return 0;
}