Here is my piece of code:
char** filename;
*(filename) = "initialize";
printf("filename = %s",*(filename));
I got this error when I tried to run it:
Run-Time Check Failure #3 - The variable 'filename' is being used without being initialized.
Is there any way to fix this?
char *a = "abcdefg";
char **fileName = &a;
C way:
#include <string.h>
#include <stdio.h>
#include <stdlib.h>
char * filename = (char*) malloc( 100 ); // reserve 100 bytes in memory
strcpy(filename,"initialize"); // copy "initialize" into the memory
printf("filename = %s",filename); // print out
free(filename); // free memory
filename = 0; // invalid pointers value is NULL
C++ way:
#include <string>
#include <iostream>
string filename("initialize"); // create string object
cout << "filename = " << filename; // write out to stanard out
You need to allocate room for filename using new or malloc. As it is, filename is just a pointer to a random area of memory you have not requested...
filename = new char*;
char** filename = new char*;
*(filename) = "initialize";
printf("filename = %s",*(filename));
But why do you need that stuff?
#Naszta's answer is the one you should listen to. But to correct all these other wrong answers on new:
size_t len = strlen("initialize") + 1;
char* sz = new char [len];
strncpy(sz, "initialize", strlen("initialize"));
The real C++ way of doing it is better, of course.
string filename = "initialize";
cout << "filename = " << filename;
For initializing char **variable you can also use the following way.
//define length
int length = 1;
std::string init_str = "your_string";
//inititlize char **var length
char **my_var = static_cast<char **>(calloc(length, sizeof(char *)));
my_var[0] = static_cast<char *>(calloc(init_str.size() + 1, sizeof(char)));
//copy string value in char **my_var
strcpy(argv[0], api_flag.c_str());
This way you can initialize for multiple values and assign values for length (N)
You haven't allocated the char* that you're trying to assign to:
char** filename = new char*;
*filename = "initialize";
Related
Assuming you read the title, here's a little example in pseudo code:
char inputChar[5][20];
{put data in array obviously}
char * outputChar;
copy(inputChar[2][7], inputChar[2][18], outputChar);
printf("%s", outputChar);
or optionally (although I prefer the above version):
char inputChar[5][20];
{put data in array obviously}
std::string outputString;
copy(inputChar[2][7], inputChar[2][18], outputString);
cout outputString; //I don't know how to use std::strings with printf
I've tried std::copy and memcpy but I can't get it to work. The result either gives me random characters that aren't part of the string, or just results in compiler errors due to me not understanding the syntax fully.
EDIT:
Here is the actual code I'm using:
(assume for this example that storeMenu already has data assigned to it)
int line = 0
int frame5 = 11;
char storeMenu[9][13];
char * temp1 = new char[12];
char * temp2 = new char[12];
std::copy(&storeMenu[line+1][0], &storeMenu[line+1][frame5-10], temp1);
std::copy(&storeMenu[line][frame5-10], &storeMenu[line][12], temp2);
To use std::copy you need a pointer to the location of the character, you are passing the character itself here. You also need to initialize outputChar.
char inputChar[5][20] = {"abc","def","ghi01234567890","jkl"};
char * outputChar = new char[20];
auto last = copy(&inputChar[2][0], &inputChar[2][5], outputChar);
*last = '\0';
printf("%s\n", outputChar);
Alternatively using std::string:
char inputChar[5][20] = {"abc","def","ghi01234567890","jkl"};
string outputChar;
copy(&inputChar[2][0], &inputChar[2][5], back_inserter(outputChar));
printf("%s\n", outputChar.c_str());
Using inputs as std::string too:
string inputChar[5] = {"abc","def","ghi01234567890","jkl"};
int fromChar = 2; // from (inclusive) ^ ^
int toChar = 5; // to (exclusive) ^
string outputChar;
copy(inputChar[2].begin()+fromChar, inputChar[2].begin()+toChar, back_inserter(outputChar));
printf("%s\n", outputChar.c_str());
cout << outputChar << endl;
I wrote a function which receives as a parameter a char pointer,then builds a new dynamic allocated char array that contains that parameter char.Then,it returns the new char array.
This is the function:
char* read_string(char *pstr)
{
char *str;
str = new char[strlen(pstr)];//allocate memory for the new char
str[strlen(pstr)] = '\0';
for(unsigned i=0;i<strlen(pstr);i++)//build the new char
str[i]=pstr[i];
return str;//then return it
}
In main I have:
int main()
{
char *Pchar = read_string("Test");
cout<<Pchar;// Outputs "Test"
delete [] Pchar;//"Program received signal SIGTRAP, Trace/breakpoint trap." error
}
I declare a char pointer in main and then make it point to the char array that is returned from the read_string function.It outputs what I want but if I want to free the memory it gives me runtime error.How can I free up the memory if I don't need to use Pchar anymore?
EDIT:Thank you all for your very informative answers.I have successfully resolved the problem.
You need to allocate more memory to have space for EOS character:
str = new char[strlen(pstr)+1];
Your specific problem is an off-by-one error:
str = new char[strlen(pstr) + 1];
// ^^^^ need one more for the '\0'
str[strlen(pstr)] = '\0';
Generally, since this is C++ and not C, it would be better to return a smart pointer so the caller knows what the ownership semantics of the pointer are:
std::unique_ptr<char[]> read_string(char *pstr)
{
std::unique_ptr<char[]> str(new char[strlen(pstr) + 1]);
// rest as before
return str;
}
It seems that the error occurs due to incorrect length of the allocated string.
You have to use the following record to allocate the string
str = new char[strlen(pstr) + 1];//allocate memory for the new char
str[strlen(pstr)] = '\0';
The function can look the following way
char* read_string( const char *pstr )
{
char *str;
size_t n = strlen( pstr );
str = new char[n + 1];//allocate memory for the new char
strcpy( str, pstr );
return str;
}
Here is my code:
#include <iostream>
#include <fstream>
using namespace std;
int main (int argc, char * argv[])
{
char * inputFileName = new char ;
char * outputFileName = new char ;
*(inputFileName)='\0';
*(outputFileName)='\0';
if(argc!=3)
{
cout<<"\n\nWRONG SET OF ARGUMENTS!!\n\nSYNTAX:\n"<<endl;
cout<<"\n./FileCp <SOURCE> <DESTINATION>\n"<<endl;
return 1;
}
strcpy(inputFileName,argv[1]);
strcpy(outputFileName,argv[2]);
cout<<"Input File Name = "<<inputFileName<<endl ;
cout<<"Output File Name = "<<outputFileName<<endl ;
}
This is the command I used:
./FileCp /Users/sumanthdamarla/Downloads/20130530_235557.jpg jkhs.jpg
And here is the output:
Input File Name = /Users/sumanthdajkhs.jpg
Output File Name = jkhs.jpg
The inputFileName is being overridden by outputFileName.
How to resolve this?
char * inputFileName = new char ;
char * outputFileName = new char ;
These two lines allocate space for exactly one character each.
strcpy(inputFileName,argv[1]);
strcpy(outputFileName,argv[2]);
These two lines, copies at least 2 characters (as otherwise it wouldn't count as an argument - an argument can't be "empty").
I would suggest that you use std::string instead of allocating memory. Then you can just do outFilename = argv[2]; and not have to worry about it's size.
Alternatively, if you are not going to use the name for anything other than keep it in a name that makes more sense than argv[2], then you could just declare const char *outFilename, and set it with outFilename = argv[2]; - but beware that modifying the contents of argv[2] is not recommended, as you don't know what is "behind it".
#include <stdio.h>
#include <string.h>
int main()
{
std::string data;
data = "hello world";
char string1[] = data;
}
If I must use char string1[] and not char *string1, is there a way I can copy content of string data into this char string1[]?
file.cpp: In function ‘int main()’:
file.cpp:13:22: error: initializer fails to determine size of ‘string1’
You can call method c_str on std::string object and copy result to your array.
Since the size of data may be variable, it cannot be copied via initialization of a static array.
One way you can do it is with dynamic allocation (which C++ string handles automatically):
char *string1 = strdup(data.c_str());
// do stuff with string1
free(string1);
If you are familiar with loops, then the easiest way is to copy the contents of string to char array one by one. As you are not going to use char pointer so you have to fix the size of char array, say 20.
int main()
{
string data;
data = "hello world";
int size = data.size(); // size of data
char string1[20]; //you can change the size of char array but it must be greater than size of data string
for (int i = 0; i < size; i++) {
string1[i] = data[i];
}
return 0;
}
Using stack memory (only if you are sure that the data.size() is less than 1000.):
char result[1000];
strcpy(result, data.c_str());
Or using heap memory:
char* result = new char[data.size() + 1];
strcpy(result, data.c_str());
// ...
delete[] result;
I would like to convert string to char array but not char*. I know how to convert string to char* (by using malloc or the way I posted it in my code) - but that's not what I want. I simply want to convert string to char[size] array. Is it possible?
#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;
int main()
{
// char to string
char tab[4];
tab[0] = 'c';
tab[1] = 'a';
tab[2] = 't';
tab[3] = '\0';
string tmp(tab);
cout << tmp << "\n";
// string to char* - but thats not what I want
char *c = const_cast<char*>(tmp.c_str());
cout << c << "\n";
//string to char
char tab2[1024];
// ?
return 0;
}
Simplest way I can think of doing it is:
string temp = "cat";
char tab2[1024];
strcpy(tab2, temp.c_str());
For safety, you might prefer:
string temp = "cat";
char tab2[1024];
strncpy(tab2, temp.c_str(), sizeof(tab2));
tab2[sizeof(tab2) - 1] = 0;
or could be in this fashion:
string temp = "cat";
char * tab2 = new char [temp.length()+1];
strcpy (tab2, temp.c_str());
Ok, i am shocked that no one really gave a good answer, now my turn. There are two cases;
A constant char array is good enough for you so you go with,
const char *array = tmp.c_str();
Or you need to modify the char array so constant is not ok, then just go with this
char *array = &tmp[0];
Both of them are just assignment operations and most of the time that is just what you need, if you really need a new copy then follow other fellows answers.
str.copy(cstr, str.length()+1); // since C++11
cstr[str.copy(cstr, str.length())] = '\0'; // before C++11
cstr[str.copy(cstr, sizeof(cstr)-1)] = '\0'; // before C++11 (safe)
It's a better practice to avoid C in C++, so std::string::copy should be the choice instead of strcpy.
Easiest way to do it would be this
std::string myWord = "myWord";
char myArray[myWord.size()+1];//as 1 char space for null is also required
strcpy(myArray, myWord.c_str());
Just copy the string into the array with strcpy.
Try this way it should be work.
string line="hello world";
char * data = new char[line.size() + 1];
copy(line.begin(), line.end(), data);
data[line.size()] = '\0';
Try strcpy(), but as Fred said, this is C++, not C
You could use strcpy(), like so:
strcpy(tab2, tmp.c_str());
Watch out for buffer overflow.
If you don't know the size of the string beforehand, you can dynamically allocate an array:
auto tab2 = std::make_unique<char[]>(temp.size() + 1);
std::strcpy(tab2.get(), temp.c_str());
If you're using C++11 or above, I'd suggest using std::snprintf over std::strcpy or std::strncpy because of its safety (i.e., you determine how many characters can be written to your buffer) and because it null-terminates the string for you (so you don't have to worry about it). It would be like this:
#include <string>
#include <cstdio>
std::string tmp = "cat";
char tab2[1024];
std::snprintf(tab2, sizeof(tab2), "%s", tmp.c_str());
In C++17, you have this alternative:
#include <string>
#include <cstdio>
#include <iterator>
std::string tmp = "cat";
char tab2[1024];
std::snprintf(tab2, std::size(tab2), "%s", tmp.c_str());
Well I know this maybe rather dumb than and simple, but I think it should work:
string n;
cin>> n;
char b[200];
for (int i = 0; i < sizeof(n); i++)
{
b[i] = n[i];
cout<< b[i]<< " ";
}