I'm trying to declare a char* using dynamic memory allocation then initialize it with a string of characters, but I keep getting this error...
Error Message:
a value of type "const char *" cannot be used to initialize an entity of type "int *"
Code:
void main() {
char *alphabet = new char();
alphabet = "abcdefghijklmnopqrstuvwxyz";
cout << alphabet;
system("pause");
}
I understand that this
void main() {
char *alphabet = new char();
cin.getline(alphabet, 255);
cout << alphabet;
system("pause");
}
will work, but I don't understand why I can't initialize it without user input;
Your question is not good. But I still give use a question. you can try as below:
#include<iostream>
using namespace std;
void showAlphabetArray(char*alp)
{
for(int i=0;i<26;i++)
{
cout<<alp[i];
}
}
int main() {
//declare and init `char` array
char *alphabet = new char[26];
//init value
for(int i=0;i<26;i++)
{
alphabet[i] = i + 97;
}
showAlphabetArray(alphabet);
system("pause");
}
You should reference to ASCII https://en.wikipedia.org/wiki/ASCII
Related
I'm getting funky output when running this code. There isn't a compile error. As far as I can tell, the problem is in my getArgs(stringstream& ss, int size) function. The strings are not copying correctly into my char* variables. I wanted a dynamic array of char* to save my command line arguments to. What am I doing wrong here?
#include "stdafx.h"
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
struct arguments
{
int argc; //number of arguments
char **argv; //array of arguments
};
void startupMsg()
{
cout << "******** CS415 SHELL ********" << endl;
}
int countArgs(stringstream& ss)
{
string temp;
int count = 0;
while (ss >> temp)
{
count++;
}
return count;
}
char** getArgs(stringstream& ss, int size)
{
ss.clear();
ss.seekg(0, ios::beg);
char **ary = new char*[size];
for (int i = 0; i < size; i++)
ary[i] = new char;
int c = 0;
string temp;
while (ss >> temp)
{
ary[c] = const_cast<char*>(temp.c_str());
c++;
}
return ary;
}
void printArgs(arguments* args)
{
for (int i = 0; i < args->argc; i++)
{
cout << args->argv[i] << " ";
}
cout << endl;
}
arguments* parseCommand(string command)
{
arguments *args = new arguments;
stringstream ss(command);
args->argc = countArgs(ss);
args->argv = getArgs(ss, args->argc);
return args;
}
int main()
{
string command;
startupMsg();
//while(true)
//{
cout << "user#linux:~$ ";
getline(cin, command);
arguments *args = parseCommand(command);
cout << args->argc << endl;
printArgs(args);
//}
}
Your problem is here:
ary[c] = const_cast<char*>(temp.c_str());
A good rule of thumb is when you find yourself needing const_cast, you're probably doing something wrong. It's not like you never need it, but it's quite an exceptional thing.
In any case, what happens here? Okay, you read into ary[0] a pointer into temp's buffer. Now you get your next argument. Best case, ary[0] and ary[1] now point to the same argument and you've lost the first one. Worst case, temp had to reallocate and now ary[0] is already a dangling pointer.
Regardless, at the end of getArgs(), temp is destroyed, and now all your likely-not-even-different pointers are dangling.
That's bad. You'll need to come up with some different.
I was trying to write a simple name generator, but I got stuck with array initialization.
Why can't I initialize 2D array like this?
const char* alphab[2][26] ={{"ABCDEFGHIJKLMNOPQRSTUVWXYZ"},
{"abcdefghijklmnopqrstuvwxyz"}};
It compiles without errors and warnings, but cout << alphab[0][5] prints nothing.
Why does this
class Sample{
private:
char alphnum[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
}
throw an "initializer-string for array of chars is too long" error, and this
char alphnum[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
class Sample{
//code
};
doesn't?
Here is my code
class NameGen {
private:
string str;
char arr[5];
const char* alphab[2][26] = {{"ABCDEFGHIJKLMNOPQRSTUVWXYZ"},
{"abcdefghijklmnopqrstuvwxyz"}
};
public:
string genName()
{
srand(time(0));
for (unsigned int i = 0; i < sizeof(arr); ++i) {
arr[i] = *alphab[(i > 0) ? 1 : 0][rand() % 25];
}
str = arr;
return str;
}
} alph;
int main()
{
cout << alph.genName() << endl;
return 0;
}
No warnings and errors. The output is: Segmentation fault (code dumped)
The answer to 1.
const char* alphab[2][26] ={{"ABCDEFGHIJKLMNOPQRSTUVWXYZ"},
{"abcdefghijklmnopqrstuvwxyz"}};
should be
const char* alphab[2] ={{"ABCDEFGHIJKLMNOPQRSTUVWXYZ"},
{"abcdefghijklmnopqrstuvwxyz"}};
since you don't have an 2-D array of pointer-to-char but just a 1-D array of pointer-to-chars. The line
arr[i] = *alphab[(i>0) ? 1: 0][rand() % 25];
should then be changed to
arr[i] = alphab[(i>0) ? 1: 0][rand() % 25];
Live example here.
The answer to 2.
Count the number of characters and add an extra one for the \0 character. You cannot have a zero-sized array as a member variable, so must specify the length, like
char alphnum[5] = "test";
Try this one:
char alphab[2][27] = {
{"abcdefghijklmnopqrstuvwxyz"},
{"ABCDEFGHIJKLMNOPQRSTUVWXYZ"}
};
Notice the use of char and char* .
char* can make an array of chars it self!
leave an extra unit for \n.
You can now easily reference the alphab.
Cout<< alphab[1][5] ; //you will get 'F'
I get this error in my code and I know why it's there. But I don't now how to fix it and achieve what I want to achieve.
list[i]=user.get; << this line of code is me trying to put a string into a char array. How would I convert the string into char while still being able to keep user.length() and getline so I can know how big my dynamic array should be?
#include<iostream>
#include<cstring>
using namespace std;
int main()
{
char *list;
string user;
int counter[26];
int data;
cout<< "Enter in a line of text (all lowercase)"<<endl;
//cin>>user;
getline(cin, user);
//cin.get(user);
cout<< user.length()<<endl;
list = new char [user.length()];
for(int i=0; i<user.length(); i++)
{
list[i]=user.get;
}
cout<< list[0]<<endl;
/*
char alphabet [26];
for (int i=0; i<25; i++)
{
data=i+97;
alphabet[i]=data;
cout<< data;
}
for (int i=0; i<25; i++)
{
if (list[i]==alphabet[i])
counter[i]++;
cout<< list[0];
}
*/
return 0;
}
You can find the string documented here.
The c_str() method returns a pointer to the underlying char array that you can memcpy or strcpy into a char array of your own.
std::size_t user_length = user.length() + 1;
char* list = new char [user_length];
strncpy(list, user.c_str(), user_length);
...
delete [] list;
Replace
list[i]=user.get;
With
list[i]=user.at(i);
Ok so this code does compile, and it does run, but it does NOT give me the correct output for EITHER the original or reverse array, just gibberish. I spent the last 4 hours trying to see where I went wrong (it wasn't working at all before and now that I got it to at least output what SHOULD be a C-string, i get gibberish). Someone please help me see where I went wrong.
#include <iostream>
#include <cstring>
using namespace std;
char* getInput();
char* getReverse(char[], int);
void displayResults(char *, char *);
const int MAX_SIZE = 21;
int main()
{
//program to create a c-string and then output the reverse order
char *original;
char *reverse;
original = getInput();
int originalSize = strlen(original);
reverse = getReverse(original, originalSize);
displayResults(original, reverse);
return 0;
}
/***************************************************
Definition of function- getInput: *
prompts the user to enter in a line of text to a *
max amount of characters. Returns a pointer to the *
C-string array. *
****************************************************/
char* getInput()
{
char *originalptr;
char original[MAX_SIZE];
cout << "Enter a word or line of text up to a max of 20 characters\nand will have it output in reverse!" << endl;
cin.getline(original, MAX_SIZE);
originalptr = original;
return originalptr;
}
char* getReverse(char *reverseThis, int size)
{
char* reverseOutput;
char reverse[MAX_SIZE];
int counter = 0;
while(*reverseThis != '\0')
{
reverse[counter] = *(reverseThis + (size - counter));
reverseThis++;
counter++;
}
reverseOutput = reverse;
return reverseOutput;
}
void displayResults(char *original, char *reverse)
{
cout << "\nYou originally entered: " << original << endl;
cout << "In reverse order: " << reverse << endl;
}
In 'getReverse' you are allocating the variable 'reverse' on the STACK meaning the data will be GONE WHEN THE FUNCTION RETURNS, no matter how many pointers reference that data.
I would declare 'reverse' in main with 'char reverse[MAX_SIZE];', then have the function take a parameter 'char reverse[]', which the function would then modify.
You are returning a pointer to a local array. The array original is destroyed after the function getInput exits. So original in main is pointing at something which no longer exists, garbage in other words. getReverse has exactly the same problem.
One way to solve this is to declare the arrays in main, and pass pointers to those arrays to the getInput and getReverse functions, for instance.
int main()
{
//program to create a c-string and then output the reverse order
char original[MAX_SIZE];
char reverse[MAX_SIZE];
getInput(original);
int originalSize = strlen(original);
getReverse(original, originalSize, reverse);
displayResults(original, reverse);
return 0;
}
void getInput(char* original)
{
cout << "Enter a word or line of text up to a max of 20 characters\nand will have it output in reverse!" << endl;
cin.getline(original, MAX_SIZE);
}
// etc
You are wasting too much char* s and data. Why not try this :
(I have not tested the code, but it must work ,probably with minor fixes,if any.)
#define MAXSIZE 20
void getinput(char *in)
{
cin.getline(in,MAXSIZE);
return;
}
void reverse(char *in);
{
int len=strlen(in);
char *store=in;
while(int i=0;i<len/2;i++)
{
char temp;
temp=*in;
*in=*(store+len);
in++;len--;
}
return;
}
int main()
{
char data[MAXSIZE];
getinput(data);
cout<<"Original :"<<data;
reverse(data);
cout<<"reverse"<<data;
}
I am making the user input a string and then comparing the reverse of it , but it is always giving 0 as result, why?
#include<iostream>
#include<string.h>
using namespace std;
int main()
{
char *str=new char[100];
cout<<"enter a string";
cin.getline(str,100);
int len=strlen(str);
char *rev=strrev(str);
int diff=strcmp(str,rev);
cout<<diff;
return 0;
}
strrev reverses a string in place. So it actually modifies your character array that str points to. If you were to do printf("%s", str); you would see that it has been reversed.
You should make a copy of the string and reverse that:
int main() {
char *str = new char[100];
char *rev = new char[100]; // You need memory for the reversed string
cout << "enter a string";
cin.getline(str, 100);
strcpy(rev, str); // Make a copy of `str` called `rev`
strrev(rev); // Reverse it.
int diff = strcmp(str, rev);
cout << diff;
return 0;
}