Febriyanto Nugroho Febriyanto Nugroho - 2 months ago 7
C Question

Why I get null ouput and is not null when using strcpy() function?

I asked this earlier here

Before this problem is already finished, but it I was still confused with null output when using

strcpy()
function.

This code snippet :

void push(char* nm, char* np, char* tel) {
if(stackMhsbaru.size != 10) {
stackMhsbaru.nama[stackMhsbaru.size + 1] = nm;
stackMhsbaru.npm[stackMhsbaru.size + 1] = np;
stackMhsbaru.telp[stackMhsbaru.size + 1] = tel;
stackMhsbaru.size++;
}
}


The above code when compiled normal, no error, the output is :

---------------------------
nama = Febri
npm = 067015021
telp = 08877
---------------------------


I change with :

void push(char* nm, char* np, char* tel) {
if(stackMhsbaru.size != 10) {
if(!nm)strcpy(stackMhsbaru.nama[stackMhsbaru.size + 1],nm);
if(!np)strcpy(stackMhsbaru.npm[stackMhsbaru.size + 1],np);
if(!tel)strcpy(stackMhsbaru.telp[stackMhsbaru.size + 1],tel);
stackMhsbaru.size++;
}
}


The above code when compiled normal, no error but the output is :

---------------------------
nama =
npm =
telp =
---------------------------


Why ? No one can explain ?

Answer

This:

if(!nm)

can be read "if not nm is non-zero", i.e. it's only true if nm is false, which it only is if it's NULL.

You don't show how you call the function, but having a NULL pointer as the second argument to strcpy() gives undefined behavior.

You meant

if(nm != NULL)

Note that this is also more explicit, and (in my opinion although here's a sea of subjectivity) more clear. If you're not an experienced C programmer, I'd say it's a good idea to use the explicit comparison.

Comments