0

I'm making a program which sorts some input words according to some rules.

To allign them, I'd like to copy "words" to "tmp" by using memcpy to use and change "tmp".

I tried to declare tmp to double pointer or array, but the only I met was segmentation fault.

How could I copy all of "words"?

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

#define MAX_WORD_LEN 30

int getInput(char*** words) {
  int count;
  int i;
  char buffer[MAX_WORD_LEN+1];

  printf("Enter the number of words: ");
  scanf("%d", &count);
  *words = malloc(count * sizeof(char*));
  printf("Enter the words: ");
  for (i = 0; i < count; i++) {
    (*words)[i] = malloc((MAX_WORD_LEN + 1) * sizeof(char));
    scanf("%s", buffer);
    strcpy((*words)[i], buffer);
  }
  return count;
}

void solve() {
  int count;
  int i;
  char ** words;
  count = getInput(&words);

  char ** tmp = malloc(count* sizeof(char*));
  memcpy(tmp, words, sizeof(char *));
}

void main() {
  solve();
  return;
}
beginner
  • 11
  • 1
  • 4
  • 2
    Why do you want to copy to `tmp`? Can't you use `words` directly? Also, remember that you are copying the *pointers* and not the contents they point to (the strings) themselves. Lastly, in the `getInput` you don't need the `buffer` array, `scanf` directly into `(*words)[i]` instead. – Some programmer dude Apr 20 '17 at 04:32
  • @Someprogrammerdude Thanks for the comment. Actually I want to reallign them such as 7531246. Put the first thing in the middle, and second one in the right of first one, and third one in the left of first one... – beginner Apr 20 '17 at 04:43
  • 1
    `void main()` --> `int main(void)`. – Sourav Ghosh Apr 20 '17 at 04:49
  • This code doesn't make much sense. Try to write it without functions first. – Lundin Apr 20 '17 at 10:58

2 Answers2

0

You started by creating an array of pointers and then called malloc for every new word.

for (i = 0; i < count; i++) {
    (*words)[i] = malloc((MAX_WORD_LEN + 1) * sizeof(char));
    scanf("%s", buffer);
    strcpy((*words)[i], buffer);
  }

(you can scanf to words direcly with out using a buffer)

Note nothing guarenties the memory allocation of all those segments is consecutive.

If you want to copy all the words, you have to do the same for tmp.

 char ** tmp = malloc(count * sizeof(char*));
  for (i = 0; i < count; i++) {
    tmp[i] = malloc((MAX_WORD_LEN + 1) * sizeof(char));
    memcpy(tmp[i], words[i], sizeof(MAX_WORD_LEN + 1));
  }
Shay Gold
  • 403
  • 4
  • 14
0

Inside function solve() you are not incrementing the pointer so as to store next string in memory:

memcpy(tmp, words, sizeof(char *));

Here you are not incrementing the pointer to store the next string.

What you need to do is:
for(i=0; i<count; i++) memcpy(&tmp[i], &words[i], sizeof(char *));

Gaurav Pathak
  • 1,065
  • 11
  • 28