I want to pass a structure to a function and store value in the structure's element. Here is my code.
#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
typedef struct {
uint32_t len;
uint16_t *arr;
} seq;
void write_seq(seq *q, int val)
{
// How to implement this function?
uint16_t *tmp;
tmp = (uint16_t *)malloc(sizeof(uint16_t));
*tmp = val;
*(q->arr + q->len) = *tmp;
q->len += 1;
}
int main(int argc, char *argv[])
{
seq q;
q.len = 0;
q.arr = NULL;
int i;
for (i = 0; i < 10; i++) {
write_seq(&q, i);
}
printf("length is %d\n", q.len);
for (i = 0; i < q.len; i++) {
printf("%d\n", *(q.arr+i));
}
return 0;
}
I want to write 0 to 9 to a memory block which q.arr points to.
I don't want to use malloc in main(), since I don't know how many bytes I need before I call write_seq. I want to locate new memory every time when write_seq is called. Here's how output should look like.
length is 10
0
1
2
3
4
5
6
7
8
9
My implementation of write_seq() would cause core dumped. I don't know how to fix it. Thank you.