[英]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.