Dex Dave Dex Dave - 23 days ago 17
C Question

Malloc a string array - C

I have been trying to understand malloc and strings, can someone help me with this please - I get a bad pointer error

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);

Answer

I think you need to try and understand yourself what you are trying to achieve. You don't need the key[2] array and I think you are confusing yourself there as you don't yet understand how pointers work. The following should work (untested)

// 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);
Comments