cvectorinitializationwarningsansi-c

Error while calling a function (pointer and vector)


Suppose that in the main I have a function a:

a(c);

and c is declared like

char* c.

The function a is actually like this:

void a(char* v)
{
    v[0] = 1;
    v[1] = 2;
}

Is this wrong? Because the program is saying that c is uninitialized in this function.

EDIT: More code:

byte* msg;

insere_msg(t_msg, argv[2], msg);

void insere_msg(int size, char name[MAX], byte* v)
{
    FILE *fp;
    int i = 10;
    int n = 0;
    char aux;

    v[0] = (byte) 4;
    v[1] = (byte) 8;
    v[2] = (byte) 15;
    v[3] = (byte) 16;
    v[4] = (byte) 23;
    v[5] = (byte) 42;
    v[6] = (byte) size>>(3*8);
    v[7] = (byte) size>>(2*8);
    v[8] = (byte) size>>(1*8);
    v[9] = (byte) size;

    fp = fopen(name, "r");

    while(n < size)
    {
        fscanf(fp, "%c", &aux);
        v[i] = (byte) aux;
        i++;
        n++;
    }
}

Solution

  • looking at your edit: You will need to allocate the memory using the malloc command somewhere.

    msg = (char *)malloc(sizeof(char) * atLeastThree);
    

    Now that msg is allocated, it can be pushed into your insere_msg function and your a function.

    You should also implement this more "safe" code:

    void a(char * v, unsigned int sizeofV){
        if(NULL != v && sizeofV >= 3){
            v[0] = 1;
            v[2] = 2;
        }else{
            printf("array v is either not allocated or not of proper size");
        }
    }
    

    you really SHOULD check to make sure that a point type has been initialized and that it is valid for the purpose of the function you are trying to pursue, before you manipulate the data being pointed to by the pointer!!!

    NOW, this will not SOLVE the problem if you have not allocated the memory, it will simply keep it from erring out.

    If you want to have EVEN SAFER code, you will pass in the unallocated pointer, and the let the function allocate and return the size. The only thing here is, that the caller if responsible for deallocating the memory.

    unsigned int a(char * v){
    
        v = (char *)malloc(sizeof(char) * Necessity);
    
        if(NULL != v){
            v[0] = 1;
            v[2] = 2;
        }else{
            printf("array v is either not allocated or not of proper size");
        }
    
        return Necessity;
    }