Malloc - string array - C

I am trying to understand malloc and strings, can someone help me with this, please - I get an error with the wrong pointer

char password[100]; char *key[2]; int textlen, keylen, i, j, k, t, s = 0; printf("password:\n") ; scanf("%s",password); keylen = strlen(password) + 1; for(i=0; i < keylen; i++) { key[i] = (char*)malloc(keylen * sizeof(char)); strcpy(key[i], password); } printf("The key is:\n\t %s", key); 
+6
source share
2 answers

I think you need to try to understand what you are trying to achieve. You do not need an array [2], and I think you are confusing yourself there because you do not yet understand how pointers work. The following should work (unverified)

 // Allow a password up to 99 characters long + room for null char char password[100]; // pointer to malloc storage for password char *key; int textlen, keylen, i, j, k, t, s = 0; // Prompt user for password printf("password:\n") ; scanf("%s",password); // Determine the length of the users password, including null character room keylen = strlen(password) + 1; // Copy password into dynamically allocated storage key = (char*)malloc(keylen * sizeof(char)); strcpy(key, password); // Print the password printf("The key is:\n\t %s", key); 
+13
source

The problem you have is:

  printf("The key is:\n\t %s", key); 

You are passing an array of pointers to printf, and what you would like to do is

  printf("The key is:\n\t %s", key[0]); 

Another problem is that you have indicated as many pointers as you have characters in your password, so you overwrite the array of pointers that you reserved, because key takes place only for two pointers, not for N, which is the main reason for your "bad pointer".

And one more thing that is not related to this error is that you should not throw malloc , nor do you need to multiply it with sizeof(char) , since by definition it will always be 1.

+5
source

Source: https://habr.com/ru/post/954252/


All Articles