I was trying to take string input, send them to thread and convert them into integers and add them. My result should have been 1+1 = 2. instead I get 49+49 = 98
main.c: In function ‘prints’:
main.c:10:7: warning: assignment to ‘int’ from ‘int *’ makes integer from pointer without a cast [-Wint-conversion]
10 | c = (int *) string;
| ^
main.c:11:9: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
11 | a = (int *) string[0];
| ^
main.c:11:7: warning: assignment to ‘int’ from ‘int *’ makes integer from pointer without a cast [-Wint-conversion]
11 | a = (int *) string[0];
| ^
main.c:12:9: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast]
12 | b = (int *) string[1];
| ^
main.c:12:7: warning: assignment to ‘int’ from ‘int *’ makes integer from pointer without a cast [-Wint-conversion]
12 | b = (int *) string[1];
| ^
In function main(): Creating a new thread
11
Given input -1341915086 and sum of 49 and 49 is 98
Here is my code. Initially I took the strings as static, sent them to my thread. The printing works fine and its getting the desired value in string.
#include<stdio.h>
#include <pthread.h>
#include<string.h>
#include <stdlib.h>
void *prints(void *str) {
int a,b,c, sum;
char *string = (char *) str;
printf("%s\n",string);
c = (int *) string;
a = (int *) string[0];
b = (int *) string[1];
sum = a+b;
printf("Given input %d and sum of %d and %d is %d",c,a,b,sum);
}
int main(int argc, char *argv[]) {
pthread_t threadID;
const char *word = "11"; // string literals are immutable
printf("In function main(): Creating a new thread\n");
int status = pthread_create(&threadID, NULL, prints, (char *)word);
pthread_join(threadID, NULL);
}