#include <stdio.h>
#include <string.h>
#include <stdlib.h>
const int debug = 1;
void copy_array(char* input, char** output, int len) {
*output = (char *)malloc(len * sizeof(*output));
if (debug) printf("copy_array: len: %x\n", len);
for (int i=0; i<len; i++) {
printf("Pre assignment: %x\n", input[i]);
*output[i] = input[i];
printf("Post assignment\n");
}
}
int main(void) {
char input[] = { 49, 27, 0x6d, 20, 0 };
char c;
char* output;
int len = strlen(input);
copy_array(input, &output, len);
return 0;
}
is example code where I am getting a segfault for reasons I don't understand at the "*output[i] =..." line.
Does anyone understand what I am doing wrong?
Edit: addressed existing comments re:
- missing stdlib.h include
- non-null-terminated array
- not using sizeof for malloc
Edit 2: the problem is resolved by Antti Haapala: [] binds more tightly than *, so "(*output)[i]" is needed.