the whole codding is correct but getting garbage value - visual-c++

The compiler is displaying garbage value when coded as follows:
#include<iostream>
using namespace std;
void summation(int value1,int value2, int sum)
{
sum = value1+value2;
}
int main()
{
int a,b,sum;
cout<<"enter first no.\n";
cin>>a ;
cout<<"enter the second no.";
cin>>b ;
summation(a,b,sum);
cout<<"the addition of two no. is :" <<sum ;
return 0;
}
Obtaining correct input on writing &sum instead of sum. Why is it so?

You are passing sum to the summation() method by value and you want to pass it by reference. Try defining your method like this:
void summation(int value1,int value2, int& sum)
{
sum = value1+value2;
}
When you pass a parameter by its value (like you did), the method creates a copy of the value of the parameter and works with the copy. In the result, the passed parameter (sum) outside of the method stays unchanged. When you pass a parameter by its reference ( int& sum ), the sum variable inside your method will be the same as the sum variable in your main method and you can make changes to it.

Related

Reading array of regs using Verilator and VPI

So I have the following register defined in my verilog
reg [31:0] register_mem [0:15]/* verilator public */;
My goal is from my verilator c++ code to read each of the 16 values stored in it.
I have found that the documentation for this VPI stuff is rather difficult to find. I still cannot figure out what a t_vpi_vecval is and what its parameters are or if it is even the right approach.
Here is my approach at reading the 5th value in the register
unsigned int read_regs() {
const std::string path = "TOP.TOP.cpu.reg_file.register_mem";
vpiHandle vh1 = vpi_handle_by_name((PLI_BYTE8*)path.c_str(), NULL);
if (!vh1) {
printf("Name %s", path.c_str());
vl_fatal(__FILE__, __LINE__, "sim_main", "No handle found: ");
}
const char* name = vpi_get_str(vpiName, vh1);
s_vpi_value v;
v.format = vpiVectorVal;
vpi_get_value(vh1, &v);
return v.value.vector[4].aval;
}
No-matter what I do here the method returns 0 suggesting that I am not looking at the register_mem array.
What am I doing wrong?
In order to get values of the array, you need to get values for every element of an array separately. VPI does not return values for the full array.
Actually the handle which you get for an array is a handle of the vpiRegArray type. It can be iterated to access every separate element.
Here is a simple code which does the iteration and prints values of every element in the array:
#include "vpi_user.h"
PLI_INT32 preg_calltf( char *txt ) {
vpiHandle hreg = vpi_handle_by_name("rarr.register_mem", 0);
vpi_printf("reg type: %s\n", vpi_get_str(vpiType, hreg)); // vpiRegArray
s_vpi_value val = {vpiDecStrVal}; // struct t_vpi_value
vpiHandle arrayIterator = vpi_iterate( vpiReg, hreg);
if( arrayIterator != NULL ) {
vpiHandle item = NULL;
while( NULL != ( item = vpi_scan( arrayIterator ) ) ) {
vpi_get_value(item, &val);
vpi_printf("item type: %s = %s\n", vpi_get_str(vpiType, item), val.value.str); // vpiReg
vpi_free_object( item );
}
}
return 0;
}
In this case I initialized the val with vpiDecStrVal. It instructs the compiler to prepare value results as a decimal string. The value is now accessible as val.value.str. You have multiple choices to get string or binary data in 2-state or 4-state representation.
For 2-state values up to 32 bit you can use an integer formatting. However, for longer values or 4-state, you need vpiVectorVal. It actually requests verilog to create 2 arrays of 32-bit integers, aval and bval. Both have sizes big enough to keep all bits of the value. Combination of bits in aval and bval represent the 4-state value of all bits in the vector.
All vpi information is available in LRM including relation diagrams and data structures. There are also some books, for example "the verilog pli handbook" by Sutherland.

Possible to Create Function with Dynamically Allocated Number of Parameters in C++?

I'm trying to write a program that will ask the user to enter "how many numbers they want to add", then add all the numbers in a function. I want to create the adding function with a dynamically allocated number of parameters such that there are X "int num{someNumber}," where X is the number of numbers the user wants to add. My current code (very rough) is:
int var = 0;
string multiply(int num);
void testing(int num, multiply(var));
int main(){}
void testing(int num, multiply(var)) {
}//end testing
//Function to append int num{num} to string
string multiply(int num) {
string declaration = "null";
for (int num = 0; num <= var; num++) {
declaration.append("int num" + num);
}//end for
return declaration;
}//end multiply
I realize that there is still work to be done, like removing the last comma, for instance, but is it possible to use a string in a function definition to declare X int num parameters?
Another similar question already exists, check out its answer: Variable number of arguments in C++?
While it is definitely possible to define functions with a variable number of arguments, you may also want to consider defining your program iteratively or recursively instead.
Functions with a variable number of arguments can be very useful at times, but can also lead to strange edge-cases like scanf("%d") which wants to scan an integer, but is not given an address to place it into. The function call is allowed, and the scanned integer overwrites a (possibly important) location in memory.

SHA1 ERROR WHILE USING TinyECC in tinyos-2.x

I am using TinyOS-2.1.2 and to achieve security techniques I am using TinyECC-2.0. I want to use the SHA1 available in tinyecc. But, when I take the hash of a value say,
uint8_t data=123;
I use the three functions of sha given in SHA1.nc namely, SHA1.reset, SHA1.update and SHA1.digest to obtain the result. But each time I run the code ie. do "make micaz sim" I get different hash results for the same data.
How to get a unique hash value for each data taken?
The code is:
#include "sha1.h"
module DisseminationC {
uses {
interface SHA1;
}
implementation{
void hash(){
uint8_t x=123;
call SHA1.context(context);
call SHA1.update(context, x, sizeof(x));
call SHA1.digest(context, Message_Digest[SHA1HashSize]);
dbg("All", "%s Hash is : %d \n", sim_time_string(), Message_Digest);
}
I made modifications in the code as shown below. Now, I am getting a hash output. But the problem is that for every different number given as input I am getting the same answer. How do I solve this issue?
Please help me..
#include "sha1.h"
module SecurityC{
uses interface Boot;
uses interface SHA1;
}
implementation{
uint8_t Message_Digest[SHA1HashSize];
SHA1Context context;
uint8_t num=123;
uint32_t length=3;
uint8_t i;
event void Boot.booted()
{
dbg("Boot", "Application booted.\n");
call SHA1.reset(&context);
while(length>0)
{
length=length/10;
call SHA1.update(&context, &num, length);
}
call SHA1.digest(&context, Message_Digest);
for(i = 0; i < SHA1HashSize; i++) {
dbg("Boot", "%s KEY IS: %x \n", sim_time_string(), Message_Digest[i]);
}
}
}
First of all, your code is bad. It lacks two braces and the function SHA1.context doesn't exist in this library (it should be SHA1.reset, I think). Moreover, Message_Digest and context aren't declared. Please provide the full code you actually use.
However, I see you have at least two serious bugs.
Firstly, you pass the value of x to SHA1.update, but you should pass a pointer to the message. Therefore, the function processes a message that lies at the address 123 in the memory (you should get a compiler warning about this). If you want to calculate a hash from the value of x, try this:
call SHA1.update(context, &x, sizeof(x));
Secondly, Message_Digest seems to be a uint8_t array of size SHA1HashSize. In the last statement you print a pointer to this array instead of its content (and again, the compiler should warn you), so you get an adress of this array in the memory. You may want to process the array in a loop:
uint8_t i;
for(i = 0; i < SHA1HashSize; ++i) {
// process Message_Digest[i], for instance print it
}

Second order functions in GLSL?

I'm looking for a way to use a function as an argument to another function in GLSL. In regular C, it can be simulated by passing a function pointer as a function argument. It also seems that other languages (like HLSL) now provide ways to deal with high-level constructs like higher-order functions, or can simulate them with clever use of HLSL structures. unfortunately I'm stuck with GLSL for now, and I can't find any way to simulate higher-order functions. Is it really impossible in current (4.2) GLSL ? Or am I missing some clever trick ?
common example of what I'm trying to achieve :
int f(someType f2, int i) {
return f2(i);
}
I'm looking for a way to use a function as an argument to another function in GLSL.
Short answer: you can't.
The closest thing to this kind of functionality you'll get in GLSL is shader subroutines. And that only allows the external OpenGL API to select which subroutine to use, not the shader itself.
So just do the switch/case statement and get it over with.
There are no higher-order functions in GLSL, but it's possible to simulate them:
#define second_order 1
#define second_order1 2
#define another_function 3
//there are no function pointers in GLSL, so I use integers instead
int call(int f2,int param1){
//instead of a function, an integer is passed as a parameter
switch(f2){
case second_order:
return param1*2;
case second_order1:
return param1*3;
}
}
int call(int f2,int param1,int param2){
//this function can be overloaded to accept more parameters
switch(f2){
case another_function:
return param1 + param2;
}
}
int f(int f2, int i) {
return call(f2,i);
}
Alternatively, this can be done using structs:
struct function{
int x;
};
function Sin(){
return function(1);
}
function Cos(){
return function(2);
}
float call(function func,float x){
if(func == Sin()){
return sin(x);
}
else if(func == Cos()){
return cos(x);
}
}
vec4 map(function func,vec4 a1){
//this function can be overloaded for different array sizes
vec4 a2;
for(int i = 0; i < 4; i++){
a2[i] = call(func,a1[i]);
}
return a2;
}
It's also possible to simulate generic second-order functions using macros:
#define map(function,input1,output1) \
for(int i = 0; i < input1.length(); i++){ \
output1[i] = function(input1[i]); \
}
This macro can be used with any type of array:
float[] arr1 = float[](1.,3.,4.);
float[arr1.length()] output1;
map(sin,arr1,output1)

Having trouble passing array to function

I am getting all kinds of errors when passing my array to this function. The function is suppose to have the user enter a name and a score and store them in 2 seperate arrays, one for the names, one for the scores. I believe I have to use pointers but have no idea on how to use them. I don't want the answer, just a push in the right direction. Here is the code:
#include <iostream>
int InputData(int &, char, int);
using namespace std;
int main()
{
char playerName[100][20];
int score[100];
int numPlayers = 0;
InputData(numPlayers, playerName, score);
return 0;
}
int InputData(int &numPlayers, char playerName[][20], int score[])
{
while (numPlayers <= 100)
{
cout << "Enter Player Name (Q to quit): ";
cin.getline(playerName, 100, ā€˜\nā€™);
if ((playerName[numPlayers] = 'Q') || (playerName[numPlayers] = 'q'))
return 0;
cout << "Enter score for " << playerName[numPlayers] <<": ";
cin >> score[numPlayers];
numPlayers++;
}
}
Ok, I made some more changes and the errors are less, must be getting close, Lol!
This looks like a school assignment and I applaud you for not asking for the answer. There are several ways to do it, but you are already fairly close in the approach that you are using. When you pass an array reference, you do not want to include the length of the array. For example, the parameter int score[100] should be int score[]. The exception, especially in your scenario, is with multidimensional arrays. In this case, you want to use char playerName[][20]. Your function declaration also needs to change to match. Don't forget InputData returns an int. Your declarations and function call are correct; you just need to adjust your function signature.
Keeping the errors aside -
InputData(numPlayers, playerName, score, size);
// ^^^^ size is no where declared
// resulting Undeclared indentifier error
Prototype mentions of taking 3 arguments but calling the function passing 4 parameters.
Hint regarding errors:
An 1D array decays to a pointer pointing to first element in the array while passing to a function.
A 2D array decays to a pointer pointing to the 1D array ( i.e., T[][size] ) while passing to a function.
Return type of main() should be int.
It seems with the given hints you corrected most of the errors. But you forgot to change the prototype. So, change -
int InputData(int &, char, int);
to
int InputData(int &, char[][20], int[]);
Why aren't you using std::string array for player names ? Use it and remove rest of the errors. Good luck.

Resources