理解指针以及如何将它们与函数一起使用时遇到很多麻烦.尝试编写一个函数,它接受任意大小的字符数组并将其保存在struct.This是我尝试但得到seg错误.
#define LENGTH 50
typedef struct{
char *pass;
int length;
}pass_t;
void createNewPassword(pass_t *password);
int main(int argc, char *argv[]) {
pass_t *password=NULL;
createNewPassword(password);
printf("%d",password->length);
}
void
createNewPassword(pass_t *password){
char c;
int i, n=LENGTH;
if (!(password->pass=malloc((n+1)*sizeof(char)))) {
printf("Out of memory, exiting.\n");
exit(EXIT_FAILURE);
}
printf("Enter a new password: ");
while((c=getchar())!='\n'){
if (i>=n){
n *= 2;
if (!(password->pass=realloc(password->pass,
(n+1)*sizeof(char)))) {
printf("Out of memory, exiting.\n");
exit(EXIT_FAILURE);
}
}
password->pass[i++]=c;
}
password->pass[i+1]='\0';
password->length=i;
}
Run Code Online (Sandbox Code Playgroud)