-5

I am learning about Pointers. This piece of code is producing run time error. I am trying to insert string in char array using Pointer to char.

#include<stdio.h>
#include<string.h>
int main()
{
    char *a[10];
    strcpy(*a,"foo");
}
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335

3 Answers3

2

You have declared a as an array of 10 pointers to char. I think you meant to declare an array of 10 char.

char a[10];

Changing the declaration would also mean you need to change the call to strcpy:

strcpy(a,"foo");

The program now looks like this:

#include<stdio.h>
#include<string.h>
int main()
{
    char a[10];
    strcpy(a,"foo");
}
Klas Lindbäck
  • 33,105
  • 5
  • 57
  • 82
2

Why Strcpy function is not working with Pointer to Array?

This declaration

char *a[10];

does not declare a pointer to an array. It is a declaration of an array of 10 pointers to objects of type char.

Moreover this array is not initialized and its elements have indeterminate values.

To declare a pointer to an array of the type char[10] you should write

char ( *a )[10];

And the pointer must be initialized by an address of an appropriate array if you are going to use it in the function strcpy.

It seems what you mean is the following.

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

int main(void) 
{
    char s[10];
    char ( *a )[10] = &s;

    strcpy( *a, "foo" );

    puts( s );

    return 0;
}

The program output is

foo

In this program there is indeed declared a pointer to a character array of the type char[10]

    char ( *a )[10] = &s;

and the pointer is initialized by the address of the array s.

And the dereferenced pointer is used in the function strcpy

    strcpy( *a, "foo" );
Vlad from Moscow
  • 301,070
  • 26
  • 186
  • 335
1

char *a[10] is as array of pointers to char, you want char a[10] which is an array of chars

Jonathan Olson
  • 1,166
  • 9
  • 19