繁体   English   中英

在结构中使用字符串时出现分段错误

[英]Segmentation fault when using string in structure

我数据库中的表只有一个Blob类型列。 我用它来存储以下结构:

struct a
{
int x;
string y;
} ;

我已经编写了一个C ++函数来使用上述结构的变量来检索此blob。 我为此使用cass_value_get_bytes函数。

问题是,如果使用上述结构,则会出现分段错误。 但是,如果我将字符串类型更改为字符数组,问题就解决了。 我不明白为什么我不能使用字符串变量,因为使用字符串比使用字符数组要整齐。

函数cass_value_get_string()cass_value_get_bytes()将指针返回到其生存期绑定到CassResult 删除结果时,值的存储也将删除。 您需要将内存复制到字符串的缓冲区中。 cass_value_get_string()也可用于blob,并且避免了必须执行reinterpret_cast<> 您可以执行以下操作:

#include <cassandra.h>
#include <string>

std::string to_string(CassValue* value) {
  const char* str;
  size_t len;
  cass_value_get_string(value, &str, &len);
  return std::string(str, len);
}

struct SomeData {
  int x;
  std::string y;
};

int main() {
  SomeData data;
  CassValue* value = NULL; /* This needs to be set from the result */
  data.y = to_string(value);
}
 You need to allocate memory dynamically,Watch this Example.

 #include<stdlib.h>
 #include<string.h>
 #include<stdio.h>
struct employee{
int no;
char name[20];
double sal;
 } ;




void main()
{

 struct employee emp={
         1234,"Aravind",20000.0
                     };
       struct employee *e=(struct employee*) malloc( sizeof(struct   employee)*1 );


  strcpy(e->name,"Byju");
  e->sal=20000.0;
  e->no=1265;
  printf("\n %d    \t %s \t %lf",emp.no,emp.name,emp.sal);
  printf("\n %d    \t %s \t %lf",e->no,e->name,e->sal);

   }
   Output:
   1234      Aravind     20000.000000
   1265      Byju        20000.000000

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM