-3

I want to know why the first code works but the second one doesn't.

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

int main()
{
    char *last, *first, *middle;
    char pres[20] = "Adams, John Quincy";
    char pres_copy[20];
    strcpy(pres_copy, pres);

    last = strtok(pres_copy, ", ");
    printf("%s", last);

    first = strtok(NULL, ", ");
    printf("%s", first);

    middle = strtok(NULL, ", ");
    printf("%s", middle);

}

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

int main()
{
    char last[20], first[20], middle[20];
    char pres[20] = "Adams, John Quincy";
    char pres_copy[20];
    strcpy(pres_copy, pres);

    last = strtok(pres_copy, ", ");
    printf("%s", last);

    first = strtok(NULL, ", ");
    printf("%s", first);

    middle = strtok(NULL, ", ");
    printf("%s", middle);

}

I thought array names were the same as pointers. But the compiler is making a distinction, since it told me type 'char [20]' and type 'char *' was incompatible.

How and why are the two data types different?

VoidPointer
  • 3,037
  • 21
  • 25
user81055
  • 441
  • 2
  • 5
  • 5

2 Answers2

2

An array is not a pointer. You're trying to assign a pointer to an array. See this C FAQ entry about arrays and pointers.

0

'char [20]' and type 'char *' are incompatible.char * can hold a pointer to char means it can store address of char not simple char.char [20] is an array of 20 character(not address of characters).

Just using the name of array makes it pointer to its first element.So passing array name as argument does not mean passing of whole array.It is just pointer to first element.

strtok returns a char * so expecting a char * as lvalue of assignment.

Dayal rai
  • 6,548
  • 22
  • 29