C deletes the value of the variable when it is passed as a parameter of a method

0

I'm doing a program in C language, the problem is that I have a variable of type int and when I pass it as a parameter, C deletes it from me.

char letra, name[] = "";
int compuesto;
compuesto = Es_Compuesto(nom, lon);//RETORNA UN INT
if (compuesto != 0){
    strncpy(name, nom, compuesto);//AQUI SE CAMBIA DE VALOR
    if (strlen(name) != compuesto) {
        name[compuesto] = '
char letra, name[] = "";
int compuesto;
compuesto = Es_Compuesto(nom, lon);//RETORNA UN INT
if (compuesto != 0){
    strncpy(name, nom, compuesto);//AQUI SE CAMBIA DE VALOR
    if (strlen(name) != compuesto) {
        name[compuesto] = '%pre%';
    }
}
'; } }

They could tell me what is happening and how I could solve it. Thanks

    
asked by Leonardo Arellano 13.12.2017 в 21:58
source

1 answer

1

Here you declare an array of size 1 (only one character is supported):

char name[] = "";

And here you store a string in that array:

strncpy(name, nom, compuesto);

The content of compuesto is deleted because the function strncpy is writing beyond the reserved memory for name , so it will inevitably start to step on memory belonging to other variables.

Consider giving name a size large enough to work without problems:

char name[100] = "";

By the way. In this part of the code:

if (strlen(name) != compuesto) {
    name[compuesto] = '
char name[] = "";
';

It's not clear to me what you want ... the function strncpy is already responsible for ending the string with a null character regardless of the length of the string, then this operation is totally unnecessary at least as and how is it raised.

    
answered by 14.12.2017 в 08:06