簡體   English   中英

我在使用字符串分配內存時遇到麻煩

[英]I'm having trouble with allocating memory with strings

我在程序的分配內存部分遇到麻煩。 我應該讀一個包含名稱列表的文件,然后為它們分配內存並將它們存儲在分配內存中。 到目前為止,這是我所擁有的,但是運行它時卻不斷遇到分段錯誤。

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

#define MAX_STRING_LEN 25

void allocate(char ***strings, int size);

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

    char **pointer;
    int size = atoi(argv[1]);

    allocate(&pointer, size);

} 

/*Will allocate memory for an array of char 
pointers and then allocate those char pointers with the size of MAX_STRING_LEN.*/
void allocate(char ***strings, int size){


    **strings = malloc( sizeof (char) * MAX_STRING_LEN);
}

當前無法正常工作,因為出現了段錯誤。 非常感謝您的事先幫助。

void allocate(char ***strings, int size)
{
   int i;

   // Here you allocate "size" string pointers...
   *strings = malloc( sizeof (char*) * size);

   // for each of those "size" pointers allocated before, here you allocate 
   //space for a string of at most MAX_STRING_LEN chars...
   for(i = 0; i < size; i++)      
      (*strings)[i] = malloc( sizeof(char) * MAX_STRING_LEN);

}

因此,如果您將大小設為10 ...

在您的主目錄中,您將有10個字符串的空間(pointer [0]到pointer [9])。

每個字符串最多可以包含24個字符(不要忘了空終止符)...

指針有點棘手,但是這里有一個技巧來處理它們:

假設您有這樣的主體:

 int main()
{
    int ***my_variable; 
} 

而且您知道如何在main內部的my_variable中進行操作 ...

要在功能中使用它,請執行以下操作:

在參數中添加一個額外的*

void f(int ****my_param)

並且只要您想在函數中使用它,就可以使用與main中相同的方法 ,但需要做一點改動:

(*my_param) = //some code

使用(* my_param)與使用main中的my_variable相同

你需要

*strings = malloc(sizeof(char *) * 10); // Here is the array
(*strings)[0] = malloc(MAX_STRING_LEN);
strcpy((*strings)[0], "The first person");
printf("First person is %s\n", (*strings)[0]);

size進來的鄧諾

暫無
暫無

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

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