簡體   English   中英

C:全局定義多維char數組

[英]C: Globally define multidimensional char array

我要做的是:讀取x個定義的最大值的字符串s_1 ... s_x。 長度l = 1000000並存儲它們。 變量x作為輸入給出,並且表示形式應全局定義。

我要怎么做是:

  1. 全局定義指向char指針的指針:

     char** S; 
  2. 在本地,從輸入中讀取x后,為x指向char的指針分配空間:

     S = (char**) malloc(sizeof(char*)*x); 
  3. 在本地為每個單個字符串s_i分配空間,並將該字符串讀取到分配的空間中:

     while(i<x){ S[i] = (char*) malloc(sizeof(char)*1000000); scanf("%s",S[i]); i++; } 

當我嘗試訪問時

    S[0][0]

它給出了內存訪問錯誤。 有任何想法嗎? 謝謝!


編輯:

我打印了數組,它工作正常,因此問題確實出在訪問代碼中。 這就是:任何人都可以看到問題所在? 因為我不能

    makeBinary(){

        printf("inside makeBinary()\n");

        S_b = malloc(sizeof(int)*1000000*x);
        length = malloc(sizeof(int)*x);
        int i;
        int j;
        for(i=0;i<x;i++){
            for(j=0;j<1000000;j++){ printf("1\n");  
                if(S[i][j]=='\0'){  printf("2\n");
                    length[i] = j; 
                        break;                  
                }else{  
                    S_b[i][j] = S[i][j]-96;     printf("3\n");      
                }   
            }
        }       
    }

它打印“ 1”,然后崩潰。 我知道代碼遠非理想,但現在我想先解決問題。 謝謝!

發生了很多事情:
更改了奇怪的強制轉換malloc的方法,該方法可以工作但很危險。
另外,您不應該使用sprintf復制內存...我不會總是分配最大值。
您可以分配正確的數量strlen()+1 ...確保將0填充到末端...類似於:

int t = 100;
char * buffer = malloc(sizeof(char*)*t);
S = &buffer;

for( int i = 0; i<10 ; i++){
    char * somestring = __FILE__;
    size_t len = strlen(somestring);
    S[i] = (char*) malloc(len+1);
    S[i][len] = 0;
    memcpy(S[i], somestring,len);
}
#include <stdio.h>
#include <stdlib.h>

char** S;

int main(void){
    int i = 0, x = 100;
    S = (char**) malloc(sizeof(char*) * x);//t --> x

    while(i<x){
        S[i] = (char*) malloc(sizeof(char)*1000000);
        if(S[i]==NULL){// check return of malloc
            perror("memory insufficient");
            return -1;
        }
        scanf("%s",S[i]);
        i++;
    }
    printf("%s\n", S[0]);//fine
    printf("%c\n", S[0][0]);//fine
    return 0;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM