指针——单个字符串与字符串数组
Pointers - single strings versus string arrays
这是一个关于指向字符串的指针和指向字符串数组的指针(复数)的问题。以下是代码-请参阅问题的注释:
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
}
test .exe中0x001899F7的未处理异常:0xC0000005:访问冲突写入位置0x00000000.
有人能纠正我吗?
你的指针数组在哪里?
char** dumber =NULL;
只是指向"指向char的指针"的指针,而不是指针数组。你需要
char** dumber = new char*[argc];
将这行添加到代码中:
dumber = malloc(100); // adjust the size as per your requirements
由于您没有为"dumber"分配任何空间,因此每次您尝试
时写一个新的字符串,你写它在位置0x00000000,写在这个
该地址导致访问冲突,因为不允许任何进程在此地址写入。
这个地址是专门为空指针保留的。
这就是我最后的结果。也许这对其他新手会有帮助,所以我想我会把它寄出去。它通过释放分配给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;
}
相关文章:
- 将C#字符串数组传递给C++
- 如何为 C 型字符串数组编写 getter 和 setter?
- 有没有办法使用 strcpy 将字符串数组复制到另一个字符串或其他数组中?
- 尝试将 c 字符串数组与分隔符连接起来
- 将字符串数组传递给接受常量字符**的函数
- 返回 C++ 中的字符串数组
- 如何从COM模块中的函数返回字符串数组?
- 无法将字符串数组声明为类成员而不是字符 (C++)
- 删除字符串数组
- 如何将字符串数组返回到 java JNI
- 将字符串数组作为函数参数传递
- C++将字符串数组的元素存储到变量中
- 循环访问还包含未使用元素的字符串数组
- 字符串数组上的 sizeof 运算符以 C++ 为单位给出不同的输出
- 乘以字符串/数组和全局数组
- 递归二进制搜索与字符串数组
- 如何初始化一个标准::字符串数组?
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- C++字符串数组的动态向量
- 给定一个等长字符串数组