简体   繁体   中英

How to store values in single dimensional character pointer array

I want store values into a character pointer pointer.I have worked out a code which is mentioned below:

#include<string.h>
#include<stdlib.h>
#include<stdio.h>

int i=0,j,n,no_stops;
char *r[10],*s[10][10];
char *a,*b;


void fetch_routes_stops()
   {
   printf("Enter the no of routes:");
   scanf("%d",&n);
   for(i=0;i<n;i++)
   {
       printf("\nEnter the route No %d:",i+1);
       scanf("%s",&a);
       r[i]=strdup(a);
   }
}

void main()
{
    fetch_routes_stops();
    for(i=0;i<n;i++)
    {
        printf("\n%s",r[i]);
    }
}

In your code,

 scanf("%s",&a);

is wrong, as a is uninitialised, and &a is not the argument you would need to pass. You need to allocate enough memory to a before passing that.

Better, you don't need to have a pointer for that itself. You can chnage your code like

  char a[128];

and then, use

  scanf("%127s", a);    //limit the input against overflow

to take the user input.

Or, if you insist to use the pointer and want to go for dynamic memory allocation, you can have a look at malloc() and family of functions. Remember, in that case also, you pass a to scanf() , not &a .

After that, please note

  1. The recommended signature of main() is int main(void) .
  2. Do not use unnecessary global variables. You can always pass the variables as function parameters to use them across functions.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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