-2
   char first[]="aa";               
   strcat(first,ar[0]);

   char *second[10];   
   strcpy(second[0],first);

I want to use strcat and strcpy. strcat works but there is an error in strcpy. how can I modified it?

esrtr
  • 99
  • 2
  • 12

1 Answers1

0

In C there are basically three kind of string/character array variables:

  1. string constant pointers
  2. character arrays where the length is set at compile time
  3. dynamic character arrays where the length is set at run-time.

For a dynamic array, the memory it uses is reserved when the program is run. The program below illustrates the three different cases. It also provided a convenient macro for memory allocation.

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

#define NEW_ARRAY(ptr, n) \
    { \
        (ptr) = malloc((n) * sizeof (ptr)[0]); \
        if ((ptr) == NULL) { \
            fprintf(stderr, "error: Memory exhausted\n"); \
            exit(EXIT_FAILURE); \
        } \
    }

int main(void)
{
    const char *s1 = "foo";
    char s2[4] = "bar";
    char *s3;

    NEW_ARRAY(s3, 4);
    strcpy(s3, "baz");

    return 0;
}
August Karlstrom
  • 10,773
  • 7
  • 38
  • 60