简体   繁体   English

C:scanf跳过第一次迭代,同时从用户通过scanf获取char *输入

[英]C : scanf skips the first iteration while taking char* inputs from user through scanf

I am trying to get Subject names from user using dynamic memory allocation and char **. 我试图使用动态内存分配和char **从用户获取主题名称。 I am not sure its the best way to do so. 我不确定这是最好的方法。

Problem : scanf is getting skipped for first iteration in for loop. 问题:在for循环的第一次迭代中跳过了scanf。 Tried with putting " %s", "\\n%s" as suggested from StackOverflow but still facing the same. 尝试按照StackOverflow的建议添加“%s”,“\\ n%s”,但仍然面临同样的问题。

Here is my code : 这是我的代码:

int nSubjects;
char **subNames;

printf("\nEnter no. of Subjects : ");
scanf("%d",&nSubjects);

subNames = malloc(nSubjects *  sizeof(char*));

 for(i=0;i<nSubjects;i++){

    *(subNames+i)= (char*)malloc(sizeof(char*));
    printf("\nEnter Subject %d name : ",i+1);
    fflush(stdin);
    scanf("%s",subNames[i]);
}

Complete code (if required): http://pastebin.com/7Ncw0mWF 完整代码(如果需要): http//pastebin.com/7Ncw0mWF

Please guide me where I am doing wrong in this code. 请指导我在此代码中出错的地方。 Any help will be highly appreciated. 任何帮助将受到高度赞赏。

You allocation is wrong for string in side loop: 对于循环中的字符串,您的分配是错误的:

*(subNames+i)= (char*)malloc(sizeof(char*));

should be: 应该:

*(subNames+i)=  malloc(sizeof(char) * (string_lenght + 1));

Additionally, don't use fflush(stdin); 另外,不要使用fflush(stdin); it causes undefined behavior on other then Microsoft compilers, Also don't cast returned address of malloc() and calloc() in C 它在其他Microsoft编译器上导致未定义的行为, 也不在C中转换malloc()calloc()返回地址

Read: Why fflush(stdin) is wrong? 阅读: 为什么fflush(stdin)错了? , and read: fflush @msdn.microsoft. ,并阅读: fflush @ msdn.microsoft。

Your malloc is wrong: 你的malloc错了:

 *(subNames[i]) = (char*)malloc(sizeof(char*));

You are trying to allocate memory for a char** which is actually then being converted to a char*. 您正在尝试为char **分配内存,而char **实际上正在转换为char *。 You also need the specify the size of length, or this will allocate a single pointer. 您还需要指定长度的大小,否则将分配单个指针。 Note: subNames[i] doesn't need to be dereferenced. 注意:subNames [i]不需要解除引用。

The below should work: 以下应该有效:

  (subNames[i]) =  (char*)malloc(sizeof(char) * (string_length + 1));

Note: you will have to declare the string length variable, maybe perhaps as 1000, and then realloc it to the strlen of the string entered afterwards. 注意:您必须声明字符串长度变量,可能为1000,然后将其重新分配给之后输入的字符串的strlen。

If your compiler is gcc and your gcc> 2.7, you can use "%ms" . 如果您的编译器是gcc而gcc> 2.7,则可以使用"%ms" this will allow scanf to allocate memory for your pointer: 这将允许scanf为您的指针分配内存:

for(i=0;i<nSubjects;i++){
    printf("\nEnter Subject %d name : ",i+1);
    scanf("%ms",&subNames[i]);
}

How to store a character string into a character pointer declared in a structure 如何将字符串存储到结构中声明的字符指针中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM