1

I am trying to take input from a user and I don't the exact length of input so therefore I am using malloc and I am splitting char by space between them and just need to print an array but I am getting warning i.e assignment makes integer from pointer without a cast on the following line:

array[i++] = p;

and my whole program is as follows:

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

int main ()
{
  char buf[] ="abc qwe ccd";
  int i;
  char *p;
  char *array=malloc(sizeof(char));
  i = 0;
  p = strtok (buf," ");
  while (p != NULL)
  {
    array[i++] = p;
    p = strtok (NULL, " ");
  }
  for (i=0;i<3; ++i)
    printf("%s\n", array[i]);
  return 0;
}

Can anyone please tell me what is wrong with my code. Thank you.

2 Answers 2

3

The following assignment is not right.

array[i++] = p;

array[i++] evaluates to type char. p is of type char*.

That's what the compiler is complaining about. Judging by the way you are using array, it needs to be of type char**.

char **array = malloc(sizeof(*array)*20); // Make it large enough for your needs.
Sign up to request clarification or add additional context in comments.

2 Comments

Thanx alot. Pointers always kill me :(
@BASEERHAIDER, you are welcome. It takes a bit getting used to.
2

I guess you wanted to create array of pointers to char instead of array of char.

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

int main (void)
{
  char buf[] ="abc qwe ccd";
  int i;
  char *p;
  /* change type of array from char* to char** */
  char **array=malloc(sizeof(char*) * sizeof(buf)); /* allocate enough memory */
  i = 0;
  p = strtok (buf," ");
  while (p != NULL)
  {
    array[i++] = p;
    p = strtok (NULL, " ");
  }
  for (i=0;i<3; ++i)
    printf("%s\n", array[i]);
  free(array); /* it is good to free whatever you allocated */
  return 0;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.