I have the following code in which I: (1) initialize an array with default values; (2) do something with the array; (3) check the array is still default. I'm unsure about (3).
#include <stdlib.h>
#include <stdio.h>
#include <inttypes.h>
#include <string.h>
#define ARRAY_MAX 10
#define DEFAULT_VALUE 0
int main(int argc, char *argv[])
{
uint32_t array[ARRAYMAX];
memset(array, DEFAULT_VALUE, sizeof(array));
do_something_with(array);
check_array_is_default(array);
return 0;
}
The way I would check if the array is only default values is the following (i.e. this is how I would write the check_array_is_default() function):
int check_array_is_default(uint32_t *array)
{
int i;
uint32_t defval = DEFAULT_VALUE;
for (i = 0; i < ARRAY_MAX; i++)
{
if (memcmp((array + i * sizeof(uint32_t)), &defval, sizeof(uint32_t)))
{
return 0;
}
}
return 1;
}
memset fills bytes, not words so you need to look at the bytes individually:
int check_array_is_default(uint32_t *array)
{
char *p = (char *)array;
int n = ARRAY_MAX * sizeof(array[0]);
for (int i = 0; i < n; i++) {
if(p[i] != DEFAULT_VALUE) {
return 0;
}
}
return 1;
}
Related
Is it possible to store data to an ostream like this
void write(std::ostream& os){
int x,y = 0; bool b = true;
os<<x<<" "<<y<<" "<<b<<std::endl;
}
and then extract data from it like this
void read(std::istream& is){
unsigned int x,y,b;
is>>x>>y>>b; // I want to take x,y,b and make store them in a object but it is not important I want to know if I can extract information from istream like this and use x,y,b
}
I tried to make a simple program to just try that
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char const *argv[]) {
std::fstream file(argv[1]);
if (!file.is_open()){
std::cerr<<"erreur"<<std::endl;
return 1;
}
bool v = false;
size_t x = 1;
size_t y = 2;
for(size_t i=0;i<4;i++) {
file<<v<<" "<<x<<" "<<y<<std::endl;
}
for (size_t j = 0; j < 4; j++) {
bool b; size_t a; size_t c;
file>>b>>a>>c;
std::cout<<b<<a<<c<<std::endl;
}
return 0;
}
but my output is this:
026422044
026422044
026422044
026422044
After closing and reopening the file my problem fixed.
#include <iostream>
#include <fstream>
#include <string>
int main(int argc, char const *argv[]) {
std::ofstream file(argv[1]);
if (!file.is_open()){
std::cerr<<"erreur"<<std::endl;
return 1;
}
bool v = false;
size_t x = 1;
size_t y = 2;
for(size_t i=0;i<4;i++) {
file<<v<<" "<<x<<" "<<y<<std::endl;
}
file.close();
std::ifstream file1(argv[1]);
if (!file1.is_open()){
std::cerr<<"erreur"<<std::endl;
return 1;
}
for (size_t j = 0; j < 4; j++) {
size_t b; size_t a; size_t c;
file1>>b>>a>>c;
std::cout<<b<<a<<c<<std::endl;
}
return 0;
}
i want to create a link between two programs throughout the execs functions .
my idea is to create function then point on it by a function pointer then send it to the other program to test it . this is my first programenter code here
1- is this possible ?
2- how ?
i get this idea because i find each time to change the function name in the main function but the remainning still as it was but if i send a pointer function as a character pointer then my programm still as it without changing
#include <iostream>
#include <cstdlib>
#include <unistd.h>
using namespace std;
void
Random(int* ,const int );
int*
selection_sort(int *arr ,const int length)
{
int i = 0,minIndex{0},tmp{0},k{0};
while(i < length-1) // T(n-1) * C1
{
minIndex = i; // Tn * C2
for(int j = i+1 ; j < length ; j++ ) // som(Ti) from i = 0 to i = length-1 )*C3.
{
if((arr)[j] < (arr)[minIndex])
minIndex = j;
}
if(minIndex != i) // Tn * C4
{
tmp = (arr)[i];
(arr)[i] = (arr)[minIndex];
(arr)[minIndex] = tmp;
}
i++;
}
return arr;
}
void
Random(int* array,const int length)
{
srand(time(nullptr));
int i{-1};
while(i++ < length)
{
array[i] = rand()%100;
sleep(0.2);
}
}
int main(int argc,char* argv[])
{
int* (*ptr)(int*,const int ) = selection_sort;
execl("/home/hellios/Documents/Algorithms/sort_Algorithms/main",(char*)ptr,0); // complete the call
return EXIT_SUCCESS;
}
sort_Algorithms/main.c
#include <iostream>
#include <unistd.h>
#include <stdlib.h>
#include <ctime>
using namespace std;
void
Random(int* array,const int length);
int
main(int argc,char* argv[])
{
int* (*ptr)(int *,const int ) =(int* (*) (int*,const int)) argv[1];
int arr1[100],k{0},*arr;
Random(arr1,100);
arr = (*ptr)(arr1,100);
//selection_sort(arr,100);
cout<<"out of selection_sort"<<endl;
for(int j = 0 ; j < 100 ; j++ )
{
printf("[%d]\t", arr[j]);
if(!(++k %10))
cout<<endl;
}
printf("\n");
return EXIT_SUCCESS ;
}
void
Random(int* array,const int length)
{
srand(time(nullptr));
int i {-1};
while(i++ < length)
{
array[i] = rand()%100;
sleep(0.2);
}
}
I have a program where I want to pass an array - in this case k[arrsize], which is a parameter of the funciton fillArray() to the other function create_file() (the same array, filled with the random numbers). However, I cannot pass the same array and I would like to ask how can this be done?
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include <time.h>
#include <stdlib.h>
using namespace std;
const int arrsize = 20;
//int a[arrsize];
fstream p;
void fillArray(int k[arrsize])
{
srand((unsigned)time(NULL));
for (int i = 0; i<20; i++)
{
if (i % 2 == 0)
{
k[i] = -(rand() % 100);
}
else
{
k[i] = (rand() % 100);
}
}
}
void create_file(int k[arrsize])
{
p.open("danni.dat", ios::out);
for (int i = 0; i<20; i++)
{
p << k[i] << endl;
}
p.close();
}
int main() {
fillArray(k);
create_file(k);
return 0;
}
You simply forget to define an array:
int main() {
int k[arrsize];
fillArray(k);
create_file(k);
}
Usually you don't want to pass the whole array, instead you might want to pass a reference to it. I suggest you to use std::array instead of a C-style arrays.
#include <array>
void fill(std::array<int, 1>& a)
{
a[0] = 0;
}
int main()
{
std::array<int, 1> a = {};
fill(a);
return 0;
}
#include "stdafx.h"
#include <vector>
#include <string>
#include <string.h>
#include <algorithm>
#include <iostream>
using namespace std;
int len = 10;
char * strNumber1 = new char[2*len+1];
char * strNumber2 = new char[2*len+1];
int cmp(const char *str1,const char *str2){
strcpy(strNumber1,*(const char**)str1);
strcat(strNumber1,*(const char**)str2);
strcpy(strNumber2,*(const char**)str2);
strcat(strNumber2,*(const char**)str1);
return strcmp(strNumber1,strNumber2);
}
string PrintMinNumber(vector<int> numbers) {
int length = numbers.size();
char **numStr = new char*[10];
for(int i = 0; i < length; i++){
sprintf(numStr[i],"%d",numbers[i]);
}
sort((char*) numStr[0],(char*)numStr[length],cmp);
// I don't know how to pass the char* from char** numStr;
string ans = "";
for(int i = 0; i < length; i++){
ans += numStr[i];
}
return ans;
}
int _tmain(int argc, _TCHAR* argv[])
{
int a[3] = {3,32,321};
vector<int> numbers(a,a+3);
cout<<PrintMinNumber(numbers);
return 0;
}
The above is my code which is used to solve the problem, which is how to get the minimum number from such as 3,321,32. We may get the result is 321323. So I need to sort the string, but I don't know how to pass char * from char** to const char*. Can you explain what I need to do?
This explanation for improvement:
If you initialize : char **numStr = new char*[10];
You actually already have 10 arrays of type char *.
You can imagine like this :
numStr = [addressOfChar-0, addressOfChar-1, ..., addressOfChar-9];
Then for the sort function, you can directly fill the begin-index and end-index parameters of Y, as below:
sort(numStr,numStr + length,cmp);
For the parameters of strcpy and strcat in function cmp (int cmp(const char *str1,const char *str2)), you do not need to cast to (const char **). Because str1 and str2 are elements of numStr or addressOfChar-N.
For strcmp you have to Compare smaller than 0, because If return -1 the result is true, You can try the code below:
bool check = (-1? True: false);
You do not forget to delete all the variables that use Memory heap (new), because it can cause leak memory.
#include <vector>
#include <string>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <cmath>
using namespace std;
int len = 10;
char * strNumber1 = new char[2*len+1];
char * strNumber2 = new char[2*len+1];
int cmp(const char *str1,const char *str2){
strcpy(strNumber1,str1);
strcat(strNumber1,str2);
strcpy(strNumber2,str2);
strcat(strNumber2,str1);
return strcmp(strNumber1, strNumber2) < 0;
}
string PrintMinNumber(vector<int> numbers) {
int length = numbers.size();
char **numStr = new char*[10];
for(int i = 0; i < length; i++){
if (numbers[i] == 0)
{
numStr[i] = new char[2];
}
else
{
numStr[i] = new char[log(numbers[i]) + 2];
}
sprintf(numStr[i],"%d",numbers[i]);
}
sort(numStr,numStr + length,cmp);
string ans = "";
for(int i = 0; i < length; i++){
ans += numStr[i];
delete[] numStr[i];
}
delete[] numStr;
return ans;
}
int main()
{
int a[] = { 321,3,32 };
vector<int> numbers(a,end(a));
cout<<PrintMinNumber(numbers);
delete[] strNumber1;
delete[] strNumber2;
return 0;
}
I'm new/noob programmer of C++, and I've this problem. I want to pass a pointer of double to a function (which will process some data on it) and read (after the process) a fixed value of that "array". I've do this:
void ReadDoubles(double* samples, int size)
{
for (int i=0; i < size; ++i)
{
*samples = i*10.1;
samples++;
}
}
int main()
{
int size = 10;
double *values=0;
ReadDoubles(values, size);
cout << *(values+3);
}
BUt of course it seems I can't init the pointer that way. I think I need to init the pointer allocating 10 values? Tried:
double *values[size];
but that's not the solution. How would you do this simple task?
You need to allocate the array at first. Here you are
#include <iostream>
void ReadDoubles( double* samples, size_t size )
{
for ( size_t i = 0; i < size; ++i )
{
*samples = i*10.1;
samples++;
}
}
int main()
{
size_t size = 10;
double *values = new double[size];
// ^^^^^^^^^^^^^^^^
ReadDoubles( values, size );
std::cout << *(values+3) << std::endl;
delete []values;
}
The program output is
30.3
If you don't want to use the operator new then there are two general approaches. Either you can declare an array as for example
int main()
{
const size_t size = 10;
//^^^^
double values[size];
// ^^^^^^^^^^^^
ReadDoubles( values, size );
std::cout << *(values+3) << std::endl;
}
or you can use standard class std::vector<double>.In this case the function should be rewritten appropriately.
For example
#include <iostream>
#include <vector>
void ReadDoubles( std::vector<double> &samples, size_t size )
{
samples.resize( size );
for ( size_t i = 0; i < size; ++i )
{
samples[i] = i*10.1;
}
}
int main()
{
size_t size = 10;
std::vector<double> values;
ReadDoubles( values, size );
std::cout << values[3] << std::endl;
}
If you are not allowed to change the RealDoubles function and you must have a function return the size then the following should work:
#include <string>
#include <iostream>
#include <math.h>
#include <cmath>
using namespace std;
void ReadDoubles(double* samples,int size)
{
for (int i=0; i < size; ++i) {
*samples = i*10.1;
samples++;
}
}
int get_size()
{
return 10;
}
int main()
{
int size = get_size(); // get size from function
//double *values=0;
double *values = new double[size] {0}; // Use new to allocate array. Optional: use {0} to init first element to 0, others default initialized to 0
ReadDoubles(values,size);
cout << *(values+3);
delete[] values;
}
If you prefer to avoid new and delete then you can let a std::vector manage the container for you:
#include <string>
#include <iostream>
#include <math.h>
#include <cmath>
#include <vector>
using namespace std;
void ReadDoubles(double* samples,int size)
{
for (int i=0; i < size; ++i) {
*samples = i*10.1;
samples++;
}
}
int get_size()
{
return 10;
}
int main()
{
int size = get_size(); // get size from function
//double *values=0;
std::vector<double> value_container(size,0); // vector will do the new and delete for us
double *values = value_container.data();
ReadDoubles(values,size);
cout << *(values+3);
} // vector destructor will do delete when it goes out of scope