读取数组时访问冲突

时间:2013-12-18 18:18:12

标签: c access-violation

我正在尝试打印一组结构并接收访问冲突。不知道如何解决这个问题。休息时,i,j,k为0。任何帮助表示赞赏。

更新:改述问题,访问结构中数据的正确方法是什么?此外qwr的答案看起来很有希望,我将有时间进行测试,谢谢。

my struct printing array of structs

1 个答案:

答案 0 :(得分:4)

关于访问冲突:

  

访问冲突通常是尝试访问CPU无法实际寻址的内存。

常见原因:

  

取消引用NULL指针。 (这是你的案例见图片)。您想要访问0x000(NULL)位置

     

尝试访问内存,程序无权(例如   作为进程上下文中的内核结构)

     

试图访问   不存在的内存地址(外部进程的地址空间)

     

尝试写入只读存储器(例如代码段)

更多:more here in wikipedia

您应该如何分配(使用您的结构):

首先你应该分配内存; 并且不要忘记你也应该编写它的免费功能

简单分配就是这样:

   //instead I advice PCurrentData notation 
   CurrentData AllCurrentData=malloc(NumProduct* sizeof *CurrentData);
   //memset so we can then check it with null
   memset(AllCurrentData,0,NumProduct* sizeof *CurrentData);
   int i,y;
   for(i=0;i<NumProduct;i++){
      //Noncontiguous allocation.Suits to string allocation,cause string lens differs
      AllCurrentData[i].data=malloc(COLUMNS*sizeof(char**));
      memset(AllCurrentData[i].data,0,COLUMNS*sizeof(char**));
      for(j=0;j<COLUMNS;j++){
         //this is just example
         //probably you want to allocate null terminating string
          int size=strlen(your_null_terminating_string)+1;//+1 for adding null,too
          AllCurrentData[i].data[j]=malloc(size*sizeof(char));
          memcpy(AllCurrentData[i].data[j],your_null_terminating_string,size);

       }

    }

另外,你的代码和正确的方法还有什么问题

另外你做错了。查看您的结构,您可以char**。但是您尝试使用2D [][]数组访问它。 为什么我们不能?因为无法保证 char** 引用连续分配,或者仅通过手动完成编译器可以使用[] [] 访问它的方式。 加上char**主要用非交错方式完成分配。因为字符串len不同

所以请注意这些:

char** 不等于 2D数组char v[][] array。因此AllCurrentData[i].data[j][k] 错误来解决char**

只有char*可以被视为一维char v[]数组。 char[]衰减到char*

所以访问应该这样做:

#define NULL 0
if(AllCurrentData[i]!=NULL && AllCurrentData[i].data[j]!=NULL){
     char* str=AllCurrentData[i].data[j];
     if(str!=NULL)
        while (str[k]!='\0'){
          printf("%c ",str[k]);++k;
         }
     }
      /*or
       while (*str){
           printf("%c ",*str);++str;
       } */
     /*but actualy you can print null terminating string directly
      (assuming you wanted this)
        if(str!=NULL)
                 printf("%s",str); 
       */

more to learn about arrays and pointers

相关问题