Skip to content

Instantly share code, notes, and snippets.

@emyfops
Last active September 1, 2025 15:39
Show Gist options
  • Select an option

  • Save emyfops/6ba22436d5ab4a6bd02e40991838f7ec to your computer and use it in GitHub Desktop.

Select an option

Save emyfops/6ba22436d5ab4a6bd02e40991838f7ec to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char*
join_string(const int elements, char** arr)
{
size_t lengths[elements];
size_t len = 0;
for (int i=0; i<elements; i++)
len += lengths[i] = strlen(arr[i]);
char* str = malloc(len * sizeof(**arr) + 1);
size_t offset = 0;
for (int i=0; i<elements; i++) {
memcpy(str+offset, arr[i], lengths[i]);
offset += lengths[i];
}
str[len] = '\0';
return str;
}
int
main(const int argc, char** argv)
{
char* eval = join_string(argc-1, ++argv);
const size_t len = strlen(eval) - 1;
char* start_end;
int result = strtol(eval, &start_end, 10);
const int start = start_end - eval;
if (start == 0) {
printf("Expected a starting number, got %c", eval[0]);
exit(-1);
}
for (int i = start; i<len; i++) {
const int peek_num = strtol(eval+i+1, NULL, 10);
switch (eval[i])
{
case '+':
result += peek_num;
break;
case '-':
result -= peek_num;
break;
case '*':
result *= peek_num;
break;
case '/':
result /= peek_num;
break;
}
}
free(eval);
printf("Result = %d", result);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment