我正在尝试在C中的结构中设置一个结构数组。直到运行时才知道数组的大小,所以我试图将数组定义为动态。我已将问题减少到下面显示的代码(每个结构中还有一些成员,但不会造成问题)。
//struct definitions
struct intStream {
int test;
};
struct io {
struct inStream **inputStream;
};
// then proceed to main
int numDevices = 4; //(derived from number of devices found at runtime)
struct io *devices;
devices->inputStream = malloc(sizeof(struct inStream) * numDevices)
// Fails on
devices->inputStream[0]->test = 1;
我仍然是C风格编程的新手,所以我对内存的理解并不完整,但是通过一些搜索,除了美学上我不喜欢的struct hack之外,我还没有找到替代解决方案。以及希望将来包含更多数组的选项。
答案 0 :(得分:3)
在此代码中,Authorization
未初始化。使用未初始化的内存调用undefined behavior。
你需要让 <dom-module id="my-component">
<template>
<div class="card">
<form is="iron-form" method="post" action="#" id="myForm">
<paper-input name="input1" focused=true always-float-label label="Input1" type="number" required></paper-input>
<paper-input name="input2" always-float-label label="Input2" type="number" required></paper-input>
<paper-button raised on-click="submit" id="submitButton">Continue</paper-button><br /><br />
<paper-button raised id="cancelButton">Cancel</paper-button>
</form>
</div>
</template>
<script>
Polymer({
is: 'my-component',
listeners: {
'myForm.iron-form-response': 'myFormResponse',
'myForm.iron-form-error': 'myFormError'
},
submit: function(event) {
if (this.$.myForm.validate()) {
this.$.submitButton.disabled = true;
this.$.myForm.disabled = true;
this.$.myForm.withCredentials = true;
this.$.myForm.action = "http://localhost:9000/handleform";
this.$.myForm.headers['Authorization'] = 'Bearer ' + tokenObtainedFromSomewhere();
this.$.myForm.headers['content-type'] = "application/json";
this.$.myForm.submit();
}
},
myFormResponse: function(e) {
alert('Success!');
},
myFormError: function(e) {
this.$.submitButton.disabled = false;
this.$.myForm.disabled = false;
alert("Failed!");
}
});
</script>
</dom-module>
指向一些有效的内存,然后才能对该指针进行去反射。
那就是说,
devices
看起来也错了。您可能想要的是
devices
然后,您还需要为每个 devices->inputStream = malloc(sizeof(struct inStream) * numDevices)
分配内存。
[通过OP修改代码,从问题中移除并添加到答案中,仅供参考]
devices->inputStream = malloc(sizeof(struct inStream *) * numDevices);