I am trying to write a function that breaks a char** math expression into its constituents. For example, "(10 - 2) / 2" would become { (, 10, -, 2, ), /, 2 }.
Because of the problem description I have been given, the return type must be char** (a pointer to a character pointer, but essentially an array of strings). I am a beginner in C/++ so I am fairly unfamiliar with pointers and memory management at the moment.
char* intTocharStar(int x) {
int length = snprintf( NULL, 0, "%d", x );
char* str = (char*)malloc( length + 1 );
snprintf( str, length + 1, "%d", x );
return str;
}
char* convertChar(char c) {
char* pointer = (char*)malloc(2*sizeof(char));
pointer[0] = c;
pointer[1] = '\0';
return pointer;
}
char **tokenize(const char* input) {
char **arr = (char**)malloc(1024 * sizeof(char*));
char op;
int num;
int index = 0;
stringstream parser(input);
while (parser) {
if (isalnum(parser.peek())) {
parser >> num;
cout << "Num " << num << '\n';
//args[index] = intTocharStar(num);
strcpy(arr[index], intTocharStar(num));
} else {
parser >> op;
cout << "Op " << op << '\n';
//args[index] = convertChar(op);
strcpy(arr[index], convertChar(num));
}
index++;
}
char** res = (char **)malloc(100 * sizeof(char*));
// remove final element, which is a duplicate
for (int i = 0; i < index - 1; i++)
res[i] = arr[i];
free(arr);
return res;
}
When I run this code, the program stops abruptly the first time the for loop runs. I decided to try debugging the program and got a segmentation fault on this line:
arr[index] = intTocharStar(num);
This is where the int parsed from the input is meant to be added to the output char** as a char*. After reading around here I tried changing this to:
strcpy(arr[index], intTocharStar(num));
But I still get the same segmentation fault. I also wrote a short program where a char* is simply strcpy'd into the first index of a char** in the main function and got this same segmentation fault, so I believe the problem is either that line where arr is accessed or this line where it is declared:
char **arr = (char**)malloc(1024 * sizeof(char*));
However from what I've read this seems to be the standard way of declaring a pointer and allocating memory to it. Is there anything I am overseeing or is there a way to further debug this?