qweeah
qweeah

Reputation: 309

C Array assignment uses brace syntax

I'm working on a display interface with C. Here is the simplified code:

    #include<stdio.h>
    #include<stdlib.h>
    #include<string.h>
    #define A_BITMAP {1,2,3}
    void getA(int **a){
        a[0]=(int*)malloc(12);
        memcpy(a[0],(int[])A_BITMAP,12);                                                                                                            
    }
    void main(){
        int* a;
        getA(&a);
        printf("%d",a[2]);
        free(a);
    }

A_BITMAP is one picture's bitmap array, and I cannot modify its code. Here is my question:

  1. Is there any way not using memcpy() to assign to the malloc(ed) area with macro A_BITMAP?

  2. Will (int[])A_BITMAP generate a large local array on stack? The picture's size is about 2M, is it safe to do so?

Upvotes: 4

Views: 151

Answers (2)

Tom Tanner
Tom Tanner

Reputation: 9354

You can cast it like that. However, casting should be avoided as it's basically telling the compiler you know better than it and disabling any sanity checks it can do. Also, as apparently you don't really know that A_BITMAP is going to be 3 ints, you're opening yourself up to a whole load of pain by hard coding the size.

Moreover, as pointed out by Sunny, it'll likely copy the array onto the stack when written like that (this depends on your compiler, but it's not something I'd like to risk). You really don't want a 2Mb array on the stack, trust me.

A couple of other points:

  • a isn't an array, it's a pointer so use *a, not a[0], as it's confusing to the reader
  • you don't return a result from main which means your program exits with an error.

You might want to consider something like this:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define A_BITMAP {1,2,3}

void getA(int **a) {
    static int data[] = A_BITMAP;
    *a = malloc(sizeof(data));
    memcpy(*a, data, sizeof(data));
}
int main(){
    int* a;
    getA(&a);
    printf("%d\n", a[2]);
    free(a);
    return 0;
}

Upvotes: 1

Sunny
Sunny

Reputation: 517

It will create the array on the stack each time the function is called. It will be better if you declare A_BITMAP as a global array as it will not be allocated on stack.

Upvotes: 0

Related Questions