C strcpy=未处理的异常:访问冲突写入位置0x00000000
我对strcpy函数有问题。使用C。 下面这段简单代码的要点是将字符串从数组复制到指针数组C strcpy=未处理的异常:访问冲突写入位置0x00000000,c,strcpy,C,Strcpy,我对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); 然后strcpy向我抛出错误: Unhandled exception: Access
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);
然后strcpy向我抛出错误:
Unhandled exception: Access violation writing location 0x00000000.
为什么??我知道这个问题可能很简单,但我真的没有任何线索。目标缓冲区尚未初始化
array\u of_pointers[0]
只是一个指针,它(在本例中基于访问冲突的错误信息)指向地址0。你需要初始化它。可能:
array_of_pointers[0] = malloc( strlen( string ) + 1 );
指针数组是由20个指针组成的数组。这样定义的话,数组中的每个条目都必须初始化才能使用。还请记住,如果确实使用malloc
(或者可能使用strdup
)分配内存,请使用free
释放内存。您需要初始化指针数组:
array_of_pointers[0] = malloc(strlen(string)+1);
或最好:
array_of_pointers[0] = strdup(string);
我做不到。_指针的数组_[0]=malloc(strlen(string)+1);VisualStudio:一个类型“Value*”的值不能被分配给一个“char”类型的实体,听起来好像你可以把它编译成C++文件。如果是这种情况,那么您需要强制转换它:array\u of_指针[0]=(char*)malloc(…)
Ok。案件得到解决。我以为定义提供了初始化,我做不到。_指针的数组_[0]=malloc(strlen(string)+1);Visual表示:“void*”类型的值不能分配给strdup解决方案将编译的“char*”类型的实体。但是,如果要直接调用malloc,则需要将malloc返回值强制转换为(char*)。另外,由于您现在使用的是堆空间而不是堆栈空间,请记住检查堆空间不足错误。