如何初始化char **?

时间:2011-07-22 19:33:26

标签: c++ visual-studio-2008 char

这是我的代码:

char** filename;
*(filename) = "initialize";
printf("filename = %s",*(filename));

我尝试运行时遇到此错误:

Run-Time Check Failure #3 - The variable 'filename' is being used without being initialized.

有什么方法可以解决这个问题吗?

6 个答案:

答案 0 :(得分:5)

char *a  =  "abcdefg";
char **fileName = &a;

答案 1 :(得分:4)

C方式:

#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 ++方式:

#include <string>
#include <iostream>

string filename("initialize");           // create string object
cout << "filename = " << filename;       // write out to stanard out

答案 2 :(得分:1)

您需要使用new或malloc为文件名分配空间。实际上,filename只是指向你未请求的随机内存区域的指针......

  filename = new char*;

答案 3 :(得分:0)

char** filename = new char*;   
*(filename) = "initialize";    
printf("filename = %s",*(filename));

但你为什么需要那些东西?

答案 4 :(得分:0)

@Naszta的回答是你应该听的。 但要纠正new上的所有其他错误答案:

size_t len = strlen("initialize") + 1;
char* sz = new char [len];
strncpy(sz, "initialize", strlen("initialize"));

真正 C ++的做法当然更好。

string filename = "initialize";
cout << "filename = " << filename;

答案 5 :(得分:-1)

您尚未分配您尝试分配的字符*:

char** filename = new char*;
*filename = "initialize";