[英]How to initialize char**?
这是我的一段代码:
char** filename;
*(filename) = "initialize";
printf("filename = %s",*(filename));
当我尝试运行它时出现此错误:
Run-Time Check Failure #3 - The variable 'filename' is being used without being initialized.
有没有什么办法解决这一问题?
char *a = "abcdefg";
char **fileName = &a;
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
您需要使用 new 或 malloc 为文件名分配空间。 事实上,文件名只是一个指向 memory 你没有请求的随机区域的指针......
filename = new char*;
char** filename = new char*;
*(filename) = "initialize";
printf("filename = %s",*(filename));
但是你为什么需要那些东西?
@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;
您尚未分配要分配的 char* :
char** filename = new char*;
*filename = "initialize";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.