LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   Passing Arrays to Functions and Program Compiles with Warnings. (https://www.linuxquestions.org/questions/linux-newbie-8/passing-arrays-to-functions-and-program-compiles-with-warnings-4175484600/)

jyunker 11-14-2013 03:00 PM

Passing Arrays to Functions and Program Compiles with Warnings.
 
I am trying to compile the following code and I get two warnings. What am I doing wrong?

The code is:

Code:

int sum1;
int sum2;

void thread1(int v[], int v_count) {
sum1 = 0;
int i;
for (i = 0; i < v_count; i++)
sum1 += v[i];
}
void thread2(int v[], int v_count) {
sum2 = 0;
int i;
for (i = 0; i < v_count; i++)
sum2 += v[i];
}


int main ( int argc, char** argv )
{
  int N = 5;
  int i;
  int array1[N];
  for (i =0; i < N; i++)
  array1[i]= i;
  thread1(array1[i],N);
  thread2(array1[i],N);
   
  return 0;
}


Now when I compile it I get the follwing output; It consists of two warnings:

cc example2.c -o exam -lm -lrt -g
example2.c: In function ‘main’:
example2.c:25: warning: passing argument 1 of ‘thread1’ makes pointer from integer without a cast
example2.c:4: note: expected ‘int *’ but argument is of type ‘int’
example2.c:26: warning: passing argument 1 of ‘thread2’ makes pointer from integer without a cast
example2.c:10: note: expected ‘int *’ but argument is of type ‘int’


The program compiles, but it gives the above warning and it then crashes during execution.


The output is:

./exam
Segmentation fault (core dumped)


Now I believe that these warnings and the program crash are all interconnected and I am not sure what is going on.

I am trying to populate an array, array1[], with integer values and then send it to one of two functions, thread1 or thread2. It does not seem to get there hence the execution crashes.

I just need to know how to fix this program so it runs.

Any help appreciated. Thanks in advance.

Respectfully,


jyunker

rknichols 11-14-2013 06:38 PM

Code:

thread1(array1[i],N);
is passing just the value of a single element of the array (and even worse, since i==N at that point it's the content of a memory location one element beyond the end of the array). When you want to reference the whole array, omit the subscript:
Code:

thread1(array1,N);

jyunker 11-15-2013 01:15 PM

modifying serial code to run on two cores usig p threads
 
Now how do I modify the code so thread1 is on one thread (say thread 1) and thread2 is on another thread (say thread 2).

I am using p threads.

Any help appreciated. Thanks in advance.

Respectfully,

jyunker

jpollard 11-15-2013 01:28 PM

I would say refer to the manual... the man page on pthread_create.

If it looks anything like mine, there is a complete example included.


All times are GMT -5. The time now is 12:14 AM.