-2
#include <stdio.h>
#include <stdlib.h>
void main()
{
    char  str[] ="asdfasdf";
    char *s;
     strcpy(s,str);
     printf("%s",s);
}

What's wrong with this code? Am I messing up with char* and char[]?

bulbasaur
  • 49
  • 1
  • 1
  • 6

2 Answers2

5

You never set s to a value, so you're invoking undefined behavior. Perhaps s = strdup(str); is better in your case?

strcpy doesn't allocate space for your copy - it assumes you've already done that. strdup allocates memory for you. As Jonathan Leffler points out in the comment - if you don't want to use dynamic memory allocation, you just need a big enough "chunk" to copy the string into.

In your case, char * and char[] types can be used interchangeably, it's just that your pointer is not set to anything valid (it could be set to anything), but your code assumes it is valid.

John3136
  • 28,809
  • 4
  • 51
  • 69
  • 1
    Or: `char buffer[32]; char *str = buffer;` to avoid dynamic memory allocation which the OP may not have encountered yet. – Jonathan Leffler Aug 04 '15 at 05:39
  • What are the cases where char* and char[] cant be used interchangeably? – bulbasaur Aug 04 '15 at 05:47
  • @bulbasaur You try to make the pedants happy and then you get a pedant going the other way ;-) When your char[] is not null terminated. `char a[3]; a[0] = 'A'; a[1]='B'; a[2]='C'` or when your char[] is really just numbers so 0 is valid (but would cause "weirdness" when a C string is expected. key being that `strcpy` expects it's char* arg to be 0 terminated string and OPs code gives it one. – John3136 Aug 04 '15 at 05:52
  • `it's just that your pointer is not set to anything,`... is it really? I mean, it's obviously set to something, which is just not _valid_,maybe? – Sourav Ghosh Aug 04 '15 at 06:19
0

char *s; in only a character pointer and currently does not point anywhere meaningful.

  1. You can point s to str, and then both will point to the same array in memory.
  2. You can create an empty character array char s[16], where you can copy the array into. In this case, s and str will be two independent arrays, and will live in different memory address in the stack.
  3. Allocate some memory to copy the string into by using malloc or strdup. Allocating memory is like taking out a loan. We need to give it back at the end of our program. Make sure to free the pointer once done using it. In this case, the two arrays live in different memory addresses, the first in the stack and second in the heap.
The Brofessor
  • 1,008
  • 6
  • 15