145 views
#include <stdio.h>

int main(void) {
char* ar;
scanf("%s",ar);
printf("%s",ar);
return 0;
}

char *test1= {"arrtest","ao", "123"};

if one can initialize array like this ,how   can input be taken by using scanf ?

| 145 views

char *ar= {"arrtest","ao", "123"};

$\rightarrow$ Here $ar$ is an array of character pointers.

$\rightarrow$  In this each character pointer i.e. ar , ar and ar is pointing to the first char of the string constants "arrtest", "ao" and  "123" respectively.

$\rightarrow$ When we execute the above line then first the string constants are created at a memory location and then the pointers start pointing to memory location of the first character of each of the string constants.

char* ar;
scanf("%s",ar);

This will not work. why ?

$\rightarrow$ Because first you are creating an array of character pointers and since they are not initialized so they are pointing to nothing.(i.e. not pointing to any memory location)

$\rightarrow$ So when you write $ar$ in $scanf$ , $a$ will not provide any address location to $scanf$. ($\because$ a is not pointing to any memory location.)

$\rightarrow$So if $scanf$ takes the input then where will it store the input ?

$\rightarrow$ In order to correct it you should first dynamically create a memory location and make the pointer point to that memory location.

$\rightarrow$ So that when you take the input using $scanf$ then the value will be stored at that memory location which you created at which the pointer is pointing.

char* ar;
ar = (char*) malloc(20); //char*  is doing typecasting.
ar = (char*) malloc(20);
ar = (char*) malloc(20);

scanf("%s",ar);
scanf("%s",ar);
scanf("%s",ar);

printf("%s",ar);
printf("%s",ar);
printf("%s",ar);

by Boss (21.6k points)
0

Cannot recognise function actually https://ideone.com/zO8aMW

0

@srestha

You are trying to overwrite a string constant which is not correct.

$ar$ is pointing to the memory location where the string constant "123" is stored.

scanf("%s",ar);

so this is trying to overwrite "123" which is a string constant with the input value.

0
no, I just decleared string inside array
0

no, I just decleared string inside array.

They are not string, they are string constants.

scanf("%s",ar);

This line is trying to overwrite the string constant.