这是一个关于指向字符串的指针与指针(复数)到字符串数组的问题。这是代码 - 请查看问题的评论:
int main(int argc, char** argv) {
// Here, we're just loading each string into an incrementing pointer and printing as we go. It's not an array of pointers. This works fine.
char* dumb = NULL;
cout << argc << endl;
for (int i = 0; i < argc; i++) {
dumb = argv[i];
cout << dumb << endl;
dumb++;
}
// Next we'll try to load the strings into an array of pointers, and print them out. This causes an error (see below).
char** dumber = NULL;
cout << argc << endl;
for (int i = 0; i < argc; i++) {
*(dumber + i) = argv[i];
cout << dumber[i] << endl;
}
return 0
}
Testing.exe中0x001899F7处的未处理异常:0xC0000005:访问冲突写入位置0x00000000。
有人可以纠正我吗?
答案 0 :(得分:2)
你的指针数组在哪里?
char** dumber =NULL;
只是指向char&#39;的指针。不是一个指针数组。 你需要
char** dumber = new char*[argc];
答案 1 :(得分:1)
将此行添加到代码中:
dumber = malloc(100); // adjust the size as per your requirements
因为每次尝试时都没有为“dumber”分配任何空间
写一个新字符串,你将它写在0x00000000位置,写在这个
location会导致访问冲突,因为不允许任何进程写入此地址
该地址专门为空指针保留。
答案 2 :(得分:1)
这就是我最终的结果。也许这会对其他新手有所帮助,所以我想 我发布了。它通过释放分配给dumber数组的内存来完成,我理解这是一件好事。
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
// int main(int argc, char** argv) { // An alternative.
// Just loading each string into the same pointer and printing as we go.
// It's not an array of pointers.
char* dumb;
cout << argc << endl;
for (int i = 0; i < argc; i++) {
dumb = argv[i];
cout << dumb << endl;
}
// Next we'll load the strings into an array of pointers, and print them out.
char** dumber = new char* [argc];
cout << argc << endl;
for (int i = 0; i < argc; i++) {
*(dumber + i) = argv[i];
cout << dumber[i] << endl;
}
// Deallocate the memory dynamically assigned by the 'new' operator for the
// pointer array.
delete[] dumber;
dumber = 0;
cin.get();
return 0;
}