简体   繁体   中英

C 2D array segmentation fault

I am writing a program, and in my program I need to Copy info from 1st 1D array into 2D array, but every time there is a \\n in 1d array, it suppose to go into different slots in 2D array. For example if 1D array is Hello\\nWorld in 2d array it will become hello/n in first slot and world in the second slot.

Here is my code But I am getting segmentation error. The array called chars is already made in my program before this step.

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

Memory allocation for a 2D array should be done like this.

words = malloc(sizeof(char *) * size1);
for(i = 0; i< size1; i++)
{
    words[i] = malloc(sizeof(char) * size2);
}

WhozCraig is right. Your malloc for words doesn't allocate enough memory and is probably causing crash for accessing memory outside the bounds. Here's why: Say numWords = 2, then the following line:

words = (char**) malloc(numWords*sizeof(char));

actually does malloc(2*1). sizeof(char) is 1.

You have only allocated 2 bytes of memory.

Did you mean sizeof(chars) in terms of allocation? That would give you the size of the 1 dimensional array. Even then you still have to copy each byte at a time from one array to another, which is not being done currently.

#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

}

I visualize pointer relations like this

图


If want to append \\n at the end a string you can use this snippet. But I think it's bad coding stile when you are hiding \\n inside variable.

int main(){
    char *str = "stackoverflow";
    int size = strlen(str);
    char str2[size+1];
    strcpy(str2, str);
    strcpy(str2+size, "\n");

    printf("%s", str2);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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