twitter
    Find out what I'm doing, Follow Me :)

In Memory Input/Output

The next operation may seem a little strange at first, but you will probably see lots of uses for it as you gain experience. Load the file named inmem.c and display it for another type of I/O, one that never accesses the outside world, but stays in the computer.

main( )
{
int numbers[5], result[5], index;
char line[80];
number[0] = 74;
number[1] = 18;
number[2] = 33;
number[3] = 30;
number[4] = 97;
sprintf(line,%d %d %d %d %d\n",numbers[0],numbers[1],
numbers[2],numbers[3],numbers[4]);
printf("%s",line);
sscanf(line,"%d %d %d %d %d",&result[4],&result[3],
(result+2),(result+1),result);
for (index = 0;index < 5;index++)
printf("The final result is %d\n",result[index]);
}



In inmem.c, we define a few variables, then assign some values to the ones named "numbers" for illustrative purposes and then use a "sprintf" function except that instead of printing the line of output to a device, it prints the line of formatted output to a character string in memory. In this case the string goes to the string variable "line", because that is the string name we inserted as the first argument in the "sprintf" function. The spaces after the 2nd %d were put there to illustrate that the next function will search properly across the line. We print the resulting string an+find that the output is identical to what it would have been by using a "printf" instead of the "sprintf" in the first place. You will see that when you compile and run the program shortly.
Since the generated string is still in memory, we can now read it with the function "sscanf". We tell the function in its first argument that "line" is the string to use for its input, and the remaining parts of the line are exactly what we would use if we were going to use the "scanf" function and read data from outside the computer. Note that it is essential that we use pointers to the data because we want to return data from a function. Just to illustrate that there are many ways to declare a pointer several methods are used, but all are pointers. The first two simply declare the address of the elements of the arrays, while the last three use the fact that "result", without the accompanying subscript, is a pointer. Just to keep it interesting, the values are read back in
reverse order. Finally the values are displayed on the monitor.