[英]C 2D array segmentation fault
我正在編寫一個程序,在我的程序中,我需要將信息從第一個1D數組復制到2D數組,但是每次在1d數組中有一個\\ n時,它都想進入2D數組中的不同插槽。 例如,如果1D數組在2d數組中是Hello \\ nWorld,它將在第一個插槽中變為hello / n,在第二個插槽中變為world。
這是我的代碼,但是我遇到了細分錯誤。 在執行此步驟之前,已在程序中創建了名為chars的數組。
words = (char**) malloc(numWords*sizeof(char));
int copyCountForChars=0;
int copyCountForWords=0;
while(copyCountForWords <= numWords)
{
words[copyCountForWords][copyCountForChars] = chars[copyCountForChars];
// printf("%c",chars[copyCountForChars]);
if(chars[copyCountForChars] == '\n')
{
// printf("%c",chars[copyCountForChars]);
copyCountForWords++;
}
copyCountForChars++;
}
2D數組的內存分配應按以下方式進行。
words = malloc(sizeof(char *) * size1);
for(i = 0; i< size1; i++)
{
words[i] = malloc(sizeof(char) * size2);
}
WhozCraig是正確的。 您的單詞malloc分配的內存不足,可能會導致超出范圍的內存訪問崩潰。 原因如下:說numWords = 2,然后說以下行:
字=(char **)malloc(numWords * sizeof(char));
實際上執行malloc(2 * 1)。 sizeof(char)為1。
您只分配了2個字節的內存。
您是說用分配來表示sizeof(chars)嗎? 這將為您提供一維數組的大小。 即使這樣,您仍必須一次將每個字節從一個數組復制到另一個數組,目前尚無此操作。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char str[100] = "hello\nworld\nstack\noverflow";
int numWords = 4; // you can handle this part
char **words = malloc(numWords * sizeof(char *));
char *tok = strtok(str, "\n");
int counter = 0;
while(tok != NULL){
words[counter] = tok;
counter++;
tok = strtok(NULL, "\n");
}
printf("%s\n", words[0]); // hello
printf("%s\n", words[1]); // world
printf("%s\n", words[2]); // stack
printf("%s\n", words[3]); // overflow
}
我像這樣可視化指針關系
如果要在字符串末尾附加\\n
,則可以使用此代碼段。 但是我認為當您將\\n
隱藏在變量中時,這是不好的編碼步驟。
int main(){
char *str = "stackoverflow";
int size = strlen(str);
char str2[size+1];
strcpy(str2, str);
strcpy(str2+size, "\n");
printf("%s", str2);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.