开发者

How to initialize char**?

开发者 https://www.devze.com 2023-03-22 13:23 出处:网络
Here is my piece of code: char** filename; *(filename) = \"initialize\"; printf(\"filename = %s\",*(filename));

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 u开发者_运维百科sed 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";
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号