指针——单个字符串与字符串数组

Pointers - single strings versus string arrays

本文关键字:字符串 数组 单个 指针      更新时间:2023-10-16

这是一个关于指向字符串的指针和指向字符串数组的指针(复数)的问题。以下是代码-请参阅问题的注释:

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;
}