我有strcpy函数的问题.使用C.这个简单代码(下面)的要点是将字符串从数组复制到指针数组.
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);
Run Code Online (Sandbox Code Playgroud)
然后strcpy抛出我的错误:
Unhandled exception: Access violation writing location 0x00000000.
Run Code Online (Sandbox Code Playgroud)
为什么?我知道这个问题可能很简单,但我真的没有线索.
目标缓冲区尚未初始化. array_of_pointers[0]只是一个指针(在这种情况下基于访问冲突的错误信息)指向地址0.您需要初始化它.可能是:
array_of_pointers[0] = malloc( strlen( string ) + 1 );
Run Code Online (Sandbox Code Playgroud)
array_of_pointers是一个20个指针的数组.这样定义,必须初始化该数组中的每个条目才能使用它.还要记住,如果您确实使用malloc(或可能strdup)分配内存,请使用free释放内存.