Originally Posted by
RyanC
what should I do to my code for working correctly?
You should declare your "RAM array" in the main function. It cannot be declared in your dynamic_allocation function because your dynamic_allocation function should compute how much space to "allocate", and then "allocate" it by assigning 'X' to elements of the array. Rather, pass a pointer to the first element of that array, along with a count of the number of bytes allocated. You also need to update the count of the number of bytes allocated.
But really, you do not need the "RAM array" at all:
Code:
#include <stdio.h>
#include <string.h>
#define MEMORY_SIZE 100
size_t compute_allocation_size(char object_type[], int object_count)
{
size_t object_size = 0;
if (strcmp(object_type, "int") == 0)
{
object_size = sizeof(int);
}
else if (strcmp(object_type, "char") == 0)
{
object_size = sizeof(char);
}
else
{
fprintf(stderr, "Unrecognised type '%s'\n", object_type);
}
return object_size * object_count;
}
void print_result(size_t allocation_count)
{
size_t i;
for (i = 0; i < allocation_count; ++i)
{
putchar('X');
}
for (i = allocation_count; i < MEMORY_SIZE; ++i)
{
putchar('*');
}
putchar('\n');
}
int main(void)
{
const char *filename = "input.txt";
FILE *fp = fopen(filename, "r");
if (fp)
{
size_t allocation_count = 0;
char line[80];
while (fgets(line, sizeof(line), fp))
{
char object_type[10];
int object_count;
if (sscanf(line, "%*[^:]: %9s %*s %d", object_type, &object_count) == 2)
{
allocation_count += compute_allocation_size(object_type, object_count);
}
else if (strcmp(line, "print the result\n") == 0)
{
print_result(allocation_count);
}
}
fclose(fp);
}
else
{
fprintf(stderr, "There was an error opening '%s'\n", filename);
}
return 0;
}
Originally Posted by
RyanC
but the plot is still need for getting the type of the arr1 and the integer number that's appearing after the arr1, e.g... "int arr1 10", I must get the type of arr1 as its "int" and the integer number "10" for doing this calculating sizeof(int)*10 which those are the number of allocated bytes!, that's all!
My past few posts have been all about getting to you come to this stage yourself. The idea is to simplify to work on the problem by itself, then apply it to your actual program, but evidently you chose not to do that. You can find my answer in the code that I posted. I hope that you learn from it, but frankly, you're becoming a help vampire, so I shall stop here.