I want to sort an array which contains names according to their length, but the following program gives a compiler error when I try to swap them using a function. Please help me identify my mistake.
void sort(char name1[][50])
{
for (int i = 0; i < 5; i++)
{
if (strlen(name1[i])>strlen(name1[i+1]))
{
char temp[50];
temp=name1[i];
name1[i]=name1[i+1];
name1[i+1]=temp;
}
}
}
Use strcpy() to copy one array to other
void sort( char name1[][50])
{
for(int i=0; i< 5; i++)
{
if(strlen(name1[i])>strlen(name1[i+1]))
{
char temp[50];
strcpy(temp,name1[i]);
strcpy(name1[i],name1[i+1]);
strcpy(name1[i+1],temp);
}
}
}
Use strcpy to copy c-string. First copy the first string into the temp string, then copy the second into the first, and finally the temp into the second string.
strcpy(temp,name1[i]);
strcpy(name1[i],name1[i+1]);
strcpy(name1[i+1],temp);
Related
In reference to this problem I need to input a 100 digit number in the program and perform operations on it. I figured I would use a char array to do it.
I wrote this code after trying for some time.
int main()
{
//int cases=10;
//while(cases--)
//{
int i;
char totalapples[102];
//char klaudia_apples[200] , natalia_apples[200];
for(i=0;totalapples[i]!='\0';i++)
{
cin>>totalapples[i];
}
//cin>>moreapples[200];
//cout<<moreapples[200];
while(i--)
{
cout<<totalapples[i];
}
//}
return 0;
}
When I run this, I get the following result:
Input : 1234657891234567981345698
Output : 987564321
Can anybody tell what is happening??
Your program invokes undefined behavior. Despite the fact the char array contains undefined values you attempt to read from it using
totalapples[i]!='\0'
in your for loop. Instead, read the whole string into a std::string:
string totalApplesStr;
cin >> totalApplesStr;
Now you can iterate over totalApplesStr:
for (char c : totalApplesStr) {
/* Do whatever you need to */
}
Or, if that isn't a logical error in your code, you can iterate from the end to the beginning:
for (auto it = totalApplesStr.rbegin(); it != totalApplesStr.rend(); ++it) {
/* Do whatever you need to */
}
Use std::string instead of a char array.
You may then use std::tranform to convert to a vector of int to do your big number computations.
You attempt to test values from an array that has not been initialized yet.
Although a char array is the least safe method you could use for this, you could fix it with an initializer:
char totalapples[102] = {0};
Also, your second loop will print the result backwards. Try incrementing to i, not decrementing from i.
You new initialize your counter/index. And there are many other improvement to be done, but your code was short
#define ARRAY_SIZE 102
int main {
char totalapples[ARRAY_SIZE];
unsigned int i = ARRAY_SIZE;
i = 0;
while (i < ARRAY_SIZE)
{
cin>>totalapples[i]; // range is 0..101
i++;
}
i = ARRAY_SIZE;
while (i > 0)
{
cout<<totalapples[i]; // range is 0..101
i--;
}
}
i just want to copy array of string to dynamical array(using new operator) without using string.h of c++
how can i copying the array?
enter code here
const int LEN=3;
int n=15;
char*s1 ;
char *s[LEN]={"music","disc","soft"};
char (*str)[LEN]=new char[n][LEN]; //i want to copy s to this array
i try to do something like this
for(int i=0; i<LEN ;i++){
strcpy(str[i],s[i]);
}
for(int i=0; i<LEN ;i++)
cout<<str[i]<<endl;
but it printing all the array in one Sequence, i think a problem with NULL terminator
i don't no how to deal with
You invert the dimension of str, try:
const int LEN = 3;
const int n = 15;
const char *s[LEN] = {"music", "disc", "soft"};
char (*str)[n] = new char[LEN][n];
for(int i = 0; i < LEN ; i++) {
strncpy(str[i], s[i], n);
}
for(int i = 0; i < LEN ; i++)
std::cout << str[i] << std::endl;
delete []str;
Live example
Look at vector.
string sArray[3] = {"aaa", "bbb", "ccc"};
vector<string> sVector;
sVector.assign(sArray, sArray+3);
Source from here
Sane C++ code would use vector or array, and also string. However, without those, pure C would often use a dynamic array of dynamic strings:
char** strs = new char*[LEN]; //a dynamic array of dynamic strings
//Alternatively, char* (*strs)[LEN]
for(int i=0; i<LEN; ++i) {
strs[i] = new char[strlen(s[i])];
strcpy(strs[i], s[i]);
}
//code goes here
for(int i=0; i<LEN; ++i)
delete[] strs[i];
delete[] strs;
strs = NULL;
However, your code is closer to a dynamic array of fixed length strings:
char **strs = new char[n][LEN]; //a dynamic array of dynamic strings
//Alternatively, char(*strs)[LEN][n], or is it char(*strs)[n][LEN]?
for(int i=0; i<LEN; ++i)
strcpy(strs[i], s[i]);
//code goes here
delete[] strs;
strs = NULL;
So here is a function in a program that I am working on for class. IN the function, I want to combinations of a 8 character hand for 3,4,5,6,7 and 8 letter words that are validated with a checkDictionary function. Everything works fine and dandy but when I want to store these created words into a 2-d array of chars (basically a 1D array of strings) I get a segmentation fault error. The lines that are apparently causing these issues are the lines such as:
strcpy(arrWords[count],letters8);
strcpy(arrWords[count],letters7);
...
^ until letters3 ^
I just want to know what exactly is wrong with me storing into the 2d array with code lines such as those. Also if you could give me any suggestion on how to accurately store these created words into the 2d array (arrWords) it would be greatly appreciated. Thank you so much for your time! :D
miscellaneous:
this program is basically scrabble
the loops that increment i & j are used to increment through a 2d array board of 10x10 that is filled with "." and placed words by the user.
-the dictionary has 40438 actual words
void computerMove(char dictionary[][45], char arrBoard[11][11], char computer[9])
{
char let1, let2, let3, let4, let5, let6, let7, let8;
// char letters3[4];
// char letters4[5];
// char letters5[6];
// char letters6[7];
// char letters7[8];
// char letters8[9];
int count = 0;
char arrWords[40438][10];
for (int i=0; i<10; i++)
{
for (int j=0; j<10; j++)
{
// if (arrBoard[i][j]!='*')
let1=arrBoard[i][j];
for (int a=0; a<8; a++)
{
let2=computer[a];
for (int b=0; b<8; b++)
{
let3=computer[b];
char letters3[4]={let1,let2,let3};
cout<<letters3<<endl;
if (searchDictionary(dictionary,letters3,40438)==true)
strcpy(arrWords[count],letters3);
count++;
for (int c=0; c<8; c++)
{
let4=computer[c];
char letters4[5]={let1,let2,let3,let4};
if (searchDictionary(dictionary,letters4,40438)==true)
strcpy(arrWords[count],letters4);
count++;
for (int d=0; d<8; d++)
{
let5=computer[d];
char letters5[6]={let1,let2,let3,let4,let5};
if (searchDictionary(dictionary,letters5,40438)==true)
strcpy(arrWords[count],letters5);
count++;
for (int e=0; e<8; e++)
{
let6=computer[e];
char letters6[7]={let1,let2,let3,let4,let5,let6};
if (searchDictionary(dictionary,letters6,40438)==true)
strcpy(arrWords[count],letters6);
count++;
for (int f=0; f<8; f++)
{
let7=computer[f];
char letters7[8]={let1,let2,let3,let4,let5,let6,let7};
if (searchDictionary(dictionary,letters7,40438)==true)
strcpy(arrWords[count],letters7);
count++;
for (int g=0; g<8; g++)
{
let8=computer[g];
char letters8[9]={let1,let2,let3,let4,let5,let6,let7,let8};
if (searchDictionary(dictionary,letters8,40438)==true)
strcpy(arrWords[count],letters8);
count++;
}
}
}
}
}
}
}
}
// cout<<"YOURE OVER HERE PAL!"<<endl;
// for (int z=0; z<50; z++)
// cout<<arrWords[z]<<endl;
}
}
Thank you so much for trying to help!
strcpy is used for copying C-strings, not arrays.
This function looks for string ending null character '\0' for the source and destination inputs so that it knows where to stop copy operation. But in the case of array, it may not find this character for a long memory sequence and you get segmentation error.
Instead, you can use std::copy() like this:
std::copy(std::begin(letters3),std::end(letters3), arrWords[count] );
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Can a local variable’s memory be accessed outside its scope?
#include <iostream>
#include <string>
using namespace std;
char* reverse(char* input)
{
char b[11];
for (int i=0; i<11; i++) {b[10-i]=input[i];}
for (int u=0; u<11; u++) {cout<<b[u];}
cout<<endl;
return &b[0];
}
int main ()
{
char ali[]="ali is good";
char *a=&ali[0];
char *b=reverse(a);
for (int i=0; i<11; b++, i++)
{
cout<<*b+i<<endl;
}
cout<<endl;
system("pause");
return 0;
}
This is a simple program to reverse a string, it works well when you print the result in the function, but when passing the pointer of the string to Main then printing it, it prints garbage-like things.
Why is it strange? because if I print *b+2 or *b+5 or whatever const I like, it works well, but if I replace the const with an int in a loop like *b+i then it does not work!!
P.S. this is not a HW!! I "was" a longtime programmer, shame on me for forgetting all of this.
Any ideas?
The variables declared inside a function are automatic storage duration objects and go ou tof scope at the end of a function (and thus are no longer valid). To allocate storage that lives longer than a function you need dynamic storage duration objects (these are allocated via new):
char *b = new char[11];
You should never return a pointer to a local variable, that why you see the error.
The local variables are allocated on the stack.
When the variable goes out of scope, the memory is de-allocated.
Now you are trying to access the variable which has been de-allocated because it has gone out of scope(and hence removed from stack)
Also
for (int i=0; i<11; b++, i++)
{
cout<<*(b+i)<<endl;
}
Why are incrementing both b and i?
You should increment just i and the not the base pointer address(b)
In summary this is the program you should use
#include<iostream>
using namespace std;
void reverse(char* input,char * output)
{
for (int i=0; i<11; i++) {output[10-i]=input[i];}
for (int u=0; u<11; u++) {cout<<output[u];}
cout<<endl;
}
int main ()
{
char ali[]="ali is good";
char *a=&ali[0];
char *b=(char *)malloc(sizeof(ali));
reverse(a,b);
for (int i=0; i<11; i++)
{
cout<<*(b+i)<<endl;
}
cout<<endl;
system("pause");
return 0;
}
Last but not least, *b+i means the value of the object pointed to by b raised by i (that is (*b)+i), not *(b+i) as you wish.
try this instead
char* reverse(char* input)
{
int len = strlen(input);
for (int i=0; i<len/2; ++i)
{
char tmp = input[i];
input[i] = input[len-i-1];
input[len-i-1] = tmp;
}
return input;
}
then you are not returning a local variable but returning the original array with the reversed string.
I have a simple table called mytable2 with only one column, name as varchar2(20).
I now have a list of names stored as vector of std::string to be inserted into the table.
I want to use executeArrayUpdate, so I must do the setDataBuffer first.
However, as I could see, people always use char[][20] to set databuffer.
This leaves me a big headache, since I have two issues here, first is to convert from vector to array, second is to convert the string to char.
1st, I tired to use vector of char[20], and this doesn't compile. Googled and they say that vector can't take char[], so I changed my vector of std::string to vector of char*.
2nd, I tried to turn the vector to arrray by using "void* p=&names[0]", as some people say this way we can use vectors just as array.
I used stmt->setDataBuffer(1,mystring,OCCI_SQLT_STR,20,NULL), and the program compiled and executed alright, but when I "select name from mytable2", it showed only some strange charaters.
Anyone has had a similiar issue before? what should I do?
My code is simple as below:
count=2;
vector<char*> mystring;
for(int i=0;i<count;i++)
{
char my[20];
strcpy_s(my,"Michael");
mystring.insert(mystring.end(),my);
}
stmt->setDataBuffer(1,&mystring[0],OCCI_SQLT_STR,20,NULL);
stmt->setBatchErrorMode (true);
stmt->executeArrayUpdate(count);
You'd need to dynamically create the char array you're putting into the vector for it to have a chance of working correctly.
I have not used OCCI, but if I had to use API that asked for char[][20], I would give it char[][20]
If you have your existing data in vector, why not just copy it across into the 2D char array? Eg.
// intialise vector with nonsense
unsigned int const VEC_SIZE = 2 ;
vector<string> v;
for (unsigned int i = 0; i < VEC_SIZE; ++i) {
stringstream s;
s << "Jon Paul " << i << endl;
v.push_back ( s.str() ) ;
}
// create the required 2D char array
unsigned int const STR_LEN = 20 ;
char c [VEC_SIZE][STR_LEN];
// copy the data from the vector of strings to the 2D char array
for (unsigned int i = 0; i < VEC_SIZE; ++i) {
string s = v[i].substr(0,STR_LEN);
char const * const cc = s.c_str();
unsigned int j = 0;
for (; j < STR_LEN && j < s.size(); ++j) {
c[i][j] = cc[j];
}
c[i][ j==STR_LEN ? 20 : j ] = 0; // write NULL character
}
I take it you've simplified your example to be a fixed size vector, so my response is going to be simplified to, with the thorny issue of dynamic allocation of 2D arrays left as an exercise for the reader...