简体   繁体   English

二维字符指针分段错误

[英]2d char pointer segmentation fault

I'm taking arguments for my C program in the linux terminal and am trying to pass them into another 2d array pointer, but I'm getting a segmentation fault where I attempt to assign the content in the argv 2d array to the strings 2d array.我正在 linux 终端中为我的 C 程序获取参数,并试图将它们传递给另一个二维数组指针,但是我遇到了分段错误,我尝试将 argv 二维数组中的内容分配给字符串二维数组. How can I successfully do this without getting an error?我怎样才能成功地做到这一点而不会出错?

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char *argv[]){

    char **strings = malloc((argc-1) * 100 * sizeof(char));

    int j = 1;
    while(*(argv + j) != NULL){
        for(int i = 0; i < strlen(*(argv + j)); i++){
            *(*(strings + j) + i) = *(*(argv + j) + i);
            printf("%c", *(*(strings + j) + i));
        }
        printf("\n");
        j++;
    }

    return 0;
}

It looks like you're trying to copy the contents of argv into memory and then print the contents.看起来您正在尝试将argv的内容复制到内存中,然后打印内容。 I wish I could draw a picture of the memory contents for you as it would be easy to see what's going on.我希望我能为你画一张记忆内容的图片,因为这样很容易看到发生了什么。 This uses a jagged array, so just google that to see some pictures.这使用了一个锯齿状的数组,所以只要谷歌一下就可以看到一些图片。 In a nutshell, char** is an array of char* .简而言之, char**是一个char*数组。 Your code is not allocating the correct size of memory.您的代码未分配正确的内存大小。 You know exactly how many elements you have through argc so you can allocate strings .您可以通过argc确切知道您拥有多少个元素,因此您可以分配strings Then for each char* of strings , you allocate enough memory to fit the data taken from argv .然后,对于strings每个char* ,您分配足够的内存以适合从argv获取的数据。 The length comes from strlen as you have, then the string is copied into the memory pointed to by elements of strings .长度来自strlen ,然后将字符串复制到strings元素指向的内存中。

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main(int argc, char* argv[]){
    char** strings = malloc((argc - 1) * sizeof(char*));

    for (int i = 0; i < argc - 1; ++i) {
        size_t len = strlen(argv[i + 1]);
        strings[i] = malloc(len + 1);
        strcpy(strings[i], argv[i + 1]);
        printf("%s\n", strings[i]);
    }

    // do what you would like with strings

    for (int i = 0; i < argc - 1; ++i)
        free(strings[i]);

    free(strings);
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM