peo965
peo965

Reputation: 39

Initializing a pointer to an array in C

I am having some issues with pointers (I am very new to coding). In main() I am trying to initialize my employee roster through InitWorkerArray so I can then print it (that function is not included below), but whenever I try CodeBlocks just shuts down. I've looked up a lot of information on pointers, but few seem to deal with arrays/structs, so any help would be appreciated. I'm sure I have a lot of errors, unfortunately.

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

typedef struct workerT_struct {
    char *pName; //employee name
    int maxName; //size, in chars, of the memory buffer to store emp name
    char *pTitle; //employee title
    int maxTitle; //size of the memory buffer created to store title
} workerT;
void initWorkerArray(workerT *pList, int siz);
void prntWorker(workerT *pList, int siz, int indx); 

int main()
{
    int maxRoster = 8;
    workerT *pRoster;
    pRoster = (workerT*)malloc(sizeof(workerT) * maxRoster);
    pRoster = NULL;
    initWorkerArray(pRoster, maxRoster);
return 0;
}
void initWorkerArray(workerT *pList, int siz) {

    pList[0].maxName = 32; 
    pList[0].maxTitle = 50;
    pList[0].pName = malloc(sizeof(char) * maxName);
    pList[0].pTitle = malloc(sizeof(char) * maxTitle);

    strcpy(pList[0].pName, "Buggy, Orson");
    strcpy(pList[0].pTitle, "Director/President");

    strcpy(pList[1].pName, "Czechs, Imelda");
    strcpy(pList[1].pTitle, "Chief Financial Officer");

    strcpy(pList[2].pName, "Hold, Levon");
    strcpy(pList[2].pTitle, "Customer Service");
    return;
}
void prntWorker(workerT *pList, int siz, int indx) {
    int i = indx;
        printf("%s, ", pList[i].pName);
        printf("%s, ", pList[i].pTitle);
        printf("\n\n");
    return;
}

Upvotes: 0

Views: 78

Answers (2)

DBug
DBug

Reputation: 2566

Also, in initWorkerArray, the calls with strcpy(pList[1]...) and strcpy(pList[2]...), pList[1].pName, etc. were never allocated, so these strcpy calls will crash.

Upvotes: 2

Some programmer dude
Some programmer dude

Reputation: 409442

The big problem is in these two lines:

pRoster = (workerT*)malloc(sizeof(workerT) * maxRoster);
pRoster = NULL;

In the first line you allocate memory and assign it to pRoster, but then in the very next line you reassign pRoster to be a null pointers. Dereferencing the null pointer later in the initWorkerArray function will lead to undefined behavior. The most likely result of this UB is a crash.

Also, in C you should not cast the result of malloc, or any other function returning void *. This won't cause any problems if you include the correct header files, but you should still not do it.

Upvotes: 2

Related Questions