-1

I'm trying to copy some 2D arrays of strings into an another one. I have 2 arrays that look like this:

char *tabA[SIZE];
char *tabB[SIZE];

I want to copy tabA[indexA] to tabB[indexB] but strcpy(tabB[indexB], tabA[indexA]) doesn't work at all, program gets crashed (but compiler doesn't return any errors).

Box Box Box Box
  • 5,094
  • 10
  • 49
  • 67
z0idb3rg
  • 461
  • 1
  • 6
  • 12

3 Answers3

1

strcpy(tabB[indexB], tabA[indexA]) doesn't work at all, program gets crashed

Possibly because tabB[indexB] is not initialized and contain NULL or invalid pointer.

Solution
Allocate memory to tabB statically using a 2D array as char tabB[SIZE1][SIZE2] = {{0}}; or dynamically as for(i = 0; i < SIZE; ++i) tabB[i] = malloc(...); or using strdup. In case of dynamic allocation, make sure you free and don't leak the memory.

Mohit Jain
  • 30,259
  • 8
  • 73
  • 100
1

I'm using memcpy from string.h, prototyped like this:

void *memcpy(void *dest, const void *src, size_t n);

The memcpy() function copies n bytes from memory area src to memory area dest.

For more detail read the manual of memcpy using the command man memcpy on a terminal.

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

const size_t SIZE=8;

int main()
{
  char *data[] = {"jan", "fev", "mar", "apr", "mai", "jun", "jul", "aug"};
  char *data2[SIZE];

  memcpy(data2, data, sizeof(char*) * SIZE);

  for (int i = 0; i < 8; ++i)
    printf("data = %s, data2 = %s\n", data[i], data2[i]);

  return (0);
}
ar-ms
  • 735
  • 6
  • 14
0
tabB[indexB] = strdup(tabA[indexA]);

works perfectly :)

z0idb3rg
  • 461
  • 1
  • 6
  • 12