-1

When I try to get a string from a function which has type void*, I only get the first character.

I tried to copy string manually without using strcpy() it gives me same problem

struct arr {
   int first
   int last.
   void **val; 
};

//I have a function which is called 
void *inspect_arr(const arr *ar, int position)
{
   ....
   return ar->val[offset];
}
//I want to inspect the array so that I can compare the strings
int main()
{
   char *str = calloc(10,sizeof(char));
   char *k = *(char*)inspect_arr(...) //I have a string in the array
  // strcpy(str,k);       Doesn't work
   strcmp(str,k);         Invalid read from valgrind
   //If array has an integer type then I would write my code like this:
   //int a = *(int*)inspect_arr(...) but I can not do the same thing for char
}

I get Segmentation fault when I run the program.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

1 Answers1

0

One problem is that first * in *(char*)inspect_arr(...).

There you dereference the pointer, getting only the first character. It's equivalent to ((char*)inspect_arr(...))[0].

To make it more troublesome, you then assign this single character to the pointer k. This doesn't make k point to the character, it make k point to whatever address corresponds to that characters encoded value. With e.g. ASCII and the character 'd' the initialization is equivalent to

char *k = 100;
Some programmer dude
  • 400,186
  • 35
  • 402
  • 621