How to pass char * from char** to const char * - c++

#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;
}

Related

transmission a function pointer to another program file

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);
}
}

how to pass array used in function to the dynamically allocated array of main?

#include<iostream>
#include<string>
using namespace std;
char *fun(const char* a)
{
int size=strlen(a);
char* str=new char[12];
for(int i=0;i<size-1;i++)
{
str[i]=a[size-i-1];
}
str[size-1]='\0';
return str;
}
main()
{
int i=0;
char a[11]={'a','y','u','s','h','r','i','k','h','r','a'};
char *p=new char[11];
p=fun(a);
for(int i=0;i<11;i++)
{
cout<<p[i]<<" ";
}
delete(ptr);
}
//having some troubles using array p in the main here please help.
There are many issues:
Here the a array is not NUL terminated, therefore strlen cannot be used on it in fun:
char a[11]={'a','y','u','s','h','r','i','k','h','r','a'};
Here you are allocating a fixed size of 12, but you need a dynamic size depending on the length of the string:
char* str=new char[12];
Then:
str[size-1]='\0';
should be:
str[size] = '\0';
otherwise your resulting string will miss the last character.
In main:
char *p=new char[11];
is pointless because you assign p right after with p=fun(a);.
You call delete(ptr);, but there is no ptr.
And finally you should also #include <string.h> be sure that strlen is defined, but one some platforms it compiles also without #include <string.h>.
You probably want this:
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
char *fun(const char* a)
{
int size = strlen(a);
char* str = new char[size + 1];
for (int i = 0; i < size; i++)
{
str[i] = a[size - i - 1];
}
str[size] = '\0';
return str;
}
int main()
{
char a[] = "ABCDE";
char *p = fun(a);
int size = strlen(p);
for (int i = 0; i < size; i++)
{
cout << p[i] << " ";
}
delete[] p;
}

Verifying changes in array after memset to default value

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;
}

Incomplete input from user

I have modified the code from my previous question, and now it looks like this:
//#include "stdafx.h"
#include <iostream>
#include <cstring>
#include <chrono>
#include <cassert>
using namespace std;
const int MAX_SIZE=10000;
const int MAX_STRINGS = 10;
char** strings=new char*[10];
int len;
char* GetLongestCommonSubstring( char* str1, char* str2 );
inline void readNumberSubstrings();
inline const char* getMaxSubstring();
void readNumberSubstrings()
{
cin >> len;
assert(len >= 1 && len <=MAX_STRINGS);
for(int i=0; i<len;i++)
strings[i]=new char[MAX_SIZE];
for(int i=0; i<len; i++)
cin >> strings[i];
}
const char* getMaxSubstring()
{
char *maxSubstring=strings[0];
auto begin = chrono::high_resolution_clock::now();
for(int i=1; i < len; i++)
maxSubstring=GetLongestCommonSubstring(maxSubstring, strings[i]);
cout << chrono::duration_cast <chrono::milliseconds> (chrono::high_resolution_clock::now()-begin).count() << endl;
return maxSubstring;
}
char* GetLongestCommonSubstring( char* string1, char* string2 )
{
if (strlen(string1)==0 || strlen(string2)==0) cerr << "error!";
int *x=new int[strlen(string2)+ 1]();
int *y= new int[strlen(string2)+ 1]();
int **previous = &x;
int **current = &y;
int max_length = 0;
int result_index = 0;
int length;
int M=strlen(string2) - 1;
for(int i = strlen(string1) - 1; i >= 0; i--)
{
for(int j = M; j >= 0; j--)
{
if(string1[i] != string2[j])
(*current)[j] = 0;
else
{
length = 1 + (*previous)[j + 1];
if (length > max_length)
{
max_length = length;
result_index = i;
}
(*current)[j] = length;
}
}
swap(previous, current);
}
delete[] x;
delete[] y;
string1[max_length+result_index]='\0';
return &(string1[result_index]);
}
int main()
{
readNumberSubstrings();
cout << getMaxSubstring() << endl;
return 0;
}
It's still solving the generalised longest common substring problem, and now it's rather fast.
But there's a catch: if a user specifies, say, 3 as a number of strings he's about to enter, and then only actually enters one string, this code waits forever.
How do I change that?
If you read from a file and the number of arguments isn't equal to the number of arguments provided, just print a nice, clean error message to the user.
"Expected 7 arguments, received 3:"
Print out the arguments you found so the user has an idea of what the program is looking at when it spits out the error.
As for human input, I agree with the comments. The program should wait until the user close it or enters all the needed arguments.

Program keeps getting segmentation fault

Coding this in CodeBlocks, this program keeps getting a seg fault. Could anyone help?
#include <string>
#include <iostream>
#include <sstream>
#include "include/hugeint.h"
using namespace std;
int main(int argc, char *argv[])
{
HugeInt h("123");
return 0;
}
my HugeInt Class (whats relevant), stores very large integers as an array of integers
class HugeInt
{
public:
HugeInt(string);
private:
DynArray dyn;
//HugeInt& reverse();
int size;
};
HugeInt::HugeInt(string input)
{
string digits = input;
for(unsigned int i = 0; i < digits.length(); i++){
dyn.add(digits.at(i) - 48);
}
size = dyn.size();
}
my dynamic array class of integers
class DynArray
{
public:
DynArray();
~DynArray();
private:
int length;
int *arr; //points to this array
int nextIndex;
};
DynArray::DynArray() {
arr = new int[10];
for (int i = 0; i < 10; i++)
arr[i] = 0;
length = 10;
nextIndex = 0; }
DynArray::~DynArray()
{
delete [] arr;
}
int DynArray::size(){
return nextIndex;
}
void DynArray::add(int val) {
int *newArr;
if (nextIndex == length) {
length = length + 10;
newArr = new int[length];
for (int i = 0; i < nextIndex; i++)
newArr[i] = arr[i];
for (int j = nextIndex; j < length; j++)
newArr[j] = 0;
delete [] arr;
arr = newArr;
}
arr[nextIndex++] = val;
}
Edit: I commented delete [] arr; out and it still seg faults :/
Edit2: OK so the code works if main is as follows. Can Anyone explain why please?
#include <string>
#include <iostream>
#include <sstream>
#include "include/hugeint.h"
using namespace std;
int main(int argc, char *argv[])
{
string in = "1234";
HugeInt h(in);
return 0;
}
You may need to initialize the DynArray in the HugeInt constructor before you start using the DynArray add() method. You didn't include the add method in the code but if it does what I imagine it does, you may have not constructed the DynArray object before using it, thus the seg fault.
The code you've posted compiles and runs without error.
I can speculate that problems are happening elsewhere because DynArray does not satisfy the rule of three.
Currently, if a DynArray is copied in any way, that copy will hold the same pointer to the same int *arr.
And when that copy is destroyed, so is the array used by all the other copies.