-2

sorry if this is a commonly asked question but I'm not sure as to why this code will not output anything:

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

int main()
{
char source[] = "hello world!";

char **destination;

strcpy(destination[0], source);

puts(destination[0]);
puts("string copied!");

return 0;
}

it looks like it is crashing at strcpy() as "string copied!" does not appear in the terminal either

LBradley
  • 11
  • 1
  • 3
    Where do you think that the copied string will be placed? What memory space does `destination[0]` point to? You need to allocate or define a buffer and give that address to your target. – Adrian Mole Aug 03 '21 at 09:35
  • 4
    Far as that goes, what does `destination` even point to ? I suggest a [decent book](https://stackoverflow.com/questions/562303/the-definitive-c-book-guide-and-list) and some quality time with the sections on pointers. Pointers are pretty fundamental to doing almost anything in C. You don't just want to learn it; you need to master it. – WhozCraig Aug 03 '21 at 09:36
  • Welcome to SO. Does your compiler tell you something about using `destination` without being initialized? You should always take care about all warnings from your compiler. – Gerhardh Aug 03 '21 at 09:40
  • 3
    Study arrays, then pointers, then strings, in that order. – Lundin Aug 03 '21 at 09:45
  • @Nagev Comments aren't exactly the right place for such code. – Gerhardh Aug 03 '21 at 11:32

1 Answers1

0

Your problem is that char **destination is an empty pointer to a pointer. destination[0] points to absolutely nothing.

Here is how you would actually do it:

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

int main()
{
  char source[] = "hello world!";

  char destination[100];

  strcpy(destination, source);

  puts(destination);
  puts("string copied!");

  return 0;
}

Or if you want to determine the size of destination dynamically:

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

int main()
{
  char source[] = "hello world!";

  char *destination = malloc(strlen(source) * sizeof(char)+1); // +1 because of null character

  strcpy(destination, source);

  puts(destination);
  puts("string copied!");


  free(destination); // IMPORTANT!!!!
  return 0;
}

Make sure you free(destination) because it is allocated on the heap and thus must be freed manually.

Marko Borković
  • 1,884
  • 1
  • 7
  • 22