why the output is last string from user?

后端 未结 7 1937
北海茫月
北海茫月 2020-12-22 10:53
#include
#include
int main()
{
    int in,i,j;
    char *arr[100],str[14];
    scanf(\"%d\",&in);
    i=0;
    while(i

        
7条回答
  •  鱼传尺愫
    2020-12-22 11:22

    Your problem is arr[i]=str; statement.

    str is a statically allocated array, and all the arr[i] are storing the base address of it.

    As the value of str get overwritten in every call to scanf(), in your case, only the last value stored in str will be printed by accessing any arr[i].

    What you need to do

    1. Allocate memory dynamically to arr[100].
    2. use strcpy() to copy the user input from str to arr[i]

    Note: Don't forget to free() the allocated memory at last.

提交回复
热议问题