0

i have a problem with the allocation of a dynamic struct array. The struct is composed of a char* field, that is another dynamic array of char. After i allocate all arrays, windows block the program when i try to modifty a struct content. Code:

 typedef struct
 {
    char *cod;
 }code;

void create_cod(code *singleCode,int codeLength);
void create_codes(code *codes, int codesNumber, int codeLength);

int main()
{
  int codesNumber=4, codeLength=10;
  code *codes;
  create_codes(codes, codesNumber, codeLength);
  codes->cod = "abcd"; /*Windows block the program here*/
}

void create_cod(code *singleCode,int codeLength)
{
    singleCode->cod = (char*)malloc(codeLength*sizeof(char));
    return;
}

void create_codes(code *codes, int codesNumber, int codeLength)
{
    codes= (code*)malloc(codesNumber*sizeof(code));
    int i=0;
    while(i<codesNumber)
    {
        create_cod(codes+i,codeLength);
        i++;
    }
    return;
}
  • possible duplicate of http://stackoverflow.com/q/19948733/5738730 – Sanjay-sopho Dec 19 '16 at 22:05
  • `create_codes(code *codes, int codesNumber, int codeLength)` does not return the pointer `codes`nor affects the calling code's `codes` from `main()`. Many dupes on this one. – chux - Reinstate Monica Dec 19 '16 at 22:06
  • Can i solve the problem with return codes; ? –  Dec 19 '16 at 22:07
  • Consider these 2 lines: `code *codes; create_codes(codes, codesNumber, codeLength);` What value does `codes` have when it is given to `create_codes()`? – chux - Reinstate Monica Dec 19 '16 at 22:07
  • Its value is an address memory –  Dec 19 '16 at 22:09
  • What's a `codice` (in function `create_codes()`)? and `numeroCodici`? – John Bollinger Dec 19 '16 at 22:11
  • 3
    C uses pass-by-value, so passing in a pointer results the pointer value being passed to the function. Altering the pointer value within the function does not affect the value in the pointer variable when the function returns. This is the same as the function not being able to alter the value of an int variable that has been passed in. – jxh Dec 19 '16 at 22:11
  • John, i fixed the code in the question. @jxh how can i solve the problem? please –  Dec 19 '16 at 22:13
  • See: http://stackoverflow.com/q/2229498/315052 – jxh Dec 19 '16 at 22:16
  • 1
    Okay, i solved returning the pointer. –  Dec 19 '16 at 22:21

0 Answers0