在结构中使用字符串时的分割故障
Segmentation fault when using string in structure
我数据库中的表有一个blob类型列。我用它来存储以下结构:
struct a
{
int x;
string y;
} ;
我已经写了一个C 功能来使用上述结构的变量来检索此斑点。我正在为此使用cass_value_get_bytes函数。
问题在于,如果使用上述结构,我会遇到细分故障。但是,如果我将字符串类型更改为字符数组,则问题可以解决。我无法理解为什么我不能使用字符串变量,因为它使用字符串比字符数组更加整洁。
功能cass_value_get_string()
和cass_value_get_bytes()
将指针返回到其寿命与CassResult
绑定的缓冲区。当结果删除时,值的内存也是如此。您需要将内存复制到字符串的缓冲区中。cass_value_get_string()
也可以用于斑点,并且避免必须执行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
相关文章:
- 分割故障C++矩阵
- C ,二进制树的高度,而不是检查我的子树是否为空,而是在检查我的子树是否是叶子节点.抛出分割故障
- 我正在为此代码分割故障
- 在执行strcpy时获取分割故障错误
- 空隙指针分割故障
- Xcode会产生分割故障,而不是例外
- OPENCV C 中的分割故障误差
- 分割故障:核心倾倒C 矢量对字符串:
- C 2D数组导致分割故障(核心倾倒)
- 分割故障/错误读数变量-C 列表
- DLSYM导致分割故障
- 使用C 中的操作员删除的分割故障
- 使用Linux X64下的Libmozjs-52(SpidermonKey)进行分割故障
- 使用长变量时分割故障(11)错误
- C - 返回字符串时的分割故障
- 创建VertexArray时的分割故障
- 向量分割故障的向量
- 从std :: fileSystem ::路径对象的类中退出时的分割故障
- C 矢量分割故障
- 基于向量的数据格式的分割故障误差