Reputation: 117
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?
Upvotes: 1
Views: 8266
Reputation: 909
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)
Upvotes: 0
Reputation: 27201
@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;
Upvotes: 0
Reputation: 670
You haven't allocated the char* that you're trying to assign to:
char** filename = new char*;
*filename = "initialize";
Upvotes: -1
Reputation: 7734
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
Upvotes: 4
Reputation: 18411
char** filename = new char*;
*(filename) = "initialize";
printf("filename = %s",*(filename));
But why do you need that stuff?
Upvotes: 0
Reputation: 28292
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*;
Upvotes: 1