2

I have a problem with strcpy function. Using C. Main point of this simple code (below) is copying a string from a array to the array of pointers.

char string[20] = "ABCDEFGH\0";
char * array_of_pointers[20];

// now I want to copy string to the first available slot;

strcpy(array_of_pointers[0],string);

Then strcpy throws me error:

Unhandled exception: Access violation writing location 0x00000000.

Why? I know that this problem is probably simple, but I really don't have a clue.

krzakov
  • 3,871
  • 11
  • 37
  • 52

2 Answers2

5

The target buffer has not been initialized. array_of_pointers[0] is just a pointer that (in this case based on the error information from the access violation) points to address 0. You need to initialize it. Possibly:

array_of_pointers[0] = malloc( strlen( string ) + 1 );

array_of_pointers is an array of 20 pointers. Defined like that, each entry in that array must be initialized before it can be used. Remember too that if you do use malloc (or possibly strdup) to allocate the memory, use free to release the memory.

Mark Wilkins
  • 40,729
  • 5
  • 57
  • 110
  • I can't do it. array_of_pointers[0] = malloc( strlen( string ) + 1 ); Visual says: a value of type "void *" cannot be assigned to a entity of type "char *" – krzakov Dec 08 '12 at 15:55
  • It sounds like you may be compiling it as a c++ file then. If that is the case, then you would need to cast it: `array_of_pointers[0] = (char*)malloc(...)` – Mark Wilkins Dec 08 '12 at 16:00
  • Ok. Case sovled. I thought definition provided initialization. – krzakov Dec 08 '12 at 16:10
1

You need to initialize array_of_pointers :

array_of_pointers[0] = malloc(strlen(string)+1);

Or best:

array_of_pointers[0] = strdup(string);
AgA
  • 2,078
  • 7
  • 33
  • 62
  • I can't do it. array_of_pointers[0] = malloc( strlen( string ) + 1 ); Visual says: a value of type "void *" cannot be assigned to a entity of type "char *" – krzakov Dec 08 '12 at 15:57
  • The strdup solution will compile. But if you want to call malloc directly you'll need to cast the malloc return value to a ( char * ) . Also as you're now using heap space not stack space remember to check for out of heap space errors. – AlgebraWinter Dec 08 '12 at 16:52