Why isn't scanf working when I try entering strings in a char pointer array?

81 Views Asked by At
#include<stdio.h>
int main(){
    char *msg[10];

    scanf("%s", msg[0]);        
    scanf("%s", msg[1]);       
    scanf("%s", msg[2]);      
    scanf("%s", msg[3]);    
}

When I try to run this code, it gives errors. Am I doing something wrong? I'm still a beginner in C language.

2

There are 2 best solutions below

1
On BEST ANSWER
char *msg[10]; 

Here msg is array of 10 char pointer and they are not initialized. If you want to store something into them, first allocate the memory dynamically.

for(int i = 0; i < 10; i++) {
  msg[i] = malloc(MAX_NO_OF_BYTES); /* MAX_NO_OF_BYTES is the no of bytes you want to allocate */
  scanf("%s",msg[i]); /* store the data into dynamically allocated memory */
}

print it & do the operation as you wanted

for(int i = 0; i < 10; i++) {
         printf("%s\n",msg[i]);
          /** operation with array of char pointer **/
 }

Once work is done, free the dynamically allocated memory using free() for each char pointer as

for(int i = 0; i < 10; i++) {
      free(msg[i]);
 }

I hope it helps.

0
On

The trouble is that char *msg[10] is a array of 10 char pointers for which you need to explicitly allocate memory or use a static array instead.

Option-1:

for (i=0; i<10; i++) 
{
  msg[i] = malloc(sizeof(char) * 100)
}

Option-2

char msg[10][100]