Getting error when using puts to output 2d char array in c when sending array as void pointer

80 views Asked by At

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>
#include <sys/time.h>
#include <unistd.h>
#include <string.h>
#define size 5


void *displayName(void *received_array){ 


char *name = received_array;


for(int i=0;i<5;i++)

     puts(name[i]);


 pthread_exit(0);

 }
 
int main(){
 pthread_t threadid1;

char name[10][50];
strcpy(name[2], "raj");
strcpy(name[3], "pol");
strcpy(name[4], "sara");*/

pthread_create(&threadid1,NULL,displayName, name);

}


In function ‘displayName’: q2v2.c:42:15: warning: passing argument 1 of ‘puts’ makes pointer from integer without a cast [-Wint-conversion] 42 | puts(name[i]); | ~~~~^~~ | | | char

2

There are 2 answers

0
MikeCAT On

You should match the type of passed pointers.

Replace

char *name = received_array;

with

char (*name)[50] = received_array;

Also don't forget to initialize name[0] and name[1] in the main() function.

1
Lundin On
<source>:9:15: warning: passing argument 1 of 'puts' makes pointer from integer without a cast [-Wint-conversion]
    9 |      puts(name[i]);
      |           ~~~~^~~
      |               |
      |               char

This warning means that puts expect a pointer but you gave it an integer type, such as a char rather than a char*.

If you still don't understand the warning after reading the text, the compiler is kind enough to point out the exact location of the bug with "ASCII art":

    9 |      puts(name[i]);
      |           ~~~~^~~
      |               |
      |               BUG HERE this is a char

When the compiler points out the exact location of the bug, it's advisable to suspect that the compiler is right and this is indeed the exact location of the bug.

That being said, you pass on a char(*)[50] to the pthread then use it as a char* inside the thread callback, which is a second bug.