Note that there are some explanatory texts on larger screens.

plurals
  1. POmemcpy a buffer and an array not working
    primarykey
    data
    text
    <p>I have a requirement in which i need to pass an empty array as a parameter to a function. And in this called function, i should be memcpy some data into the passed array. So i have written a small example which is same as my requirement. Below is its code:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; void printArr(int *a) { int i; int *b=(int*)malloc(sizeof(int)*10); printf("\n\nEnter 10 lements:\n"); for(i=0;i&lt;10;i++) scanf("%d",&amp;b[i]); printf("\nContents of array b:\n"); for(i=0;i&lt;10;i++) printf("%d\t",b[i]); printf("\n"); memcpy(a,b,10); printf("\nContents of array a:\n"); for(i=0;i&lt;10;i++) printf("%d\t",a[i]); printf("\n"); } int main() { int a[10]; printArr(a); return 0; } </code></pre> <p>In the above example, i'm sending an array from the main function to the printArr function. Now in the called function, data will be memcpy into the array. When the array contents are printed i get some junk values. Also the compilation gives a warning as shown below:</p> <pre><code>$ gcc -o arr array.c array.c: In function ‘printArr’: array.c:15:2: warning: incompatible implicit declaration of built-in function ‘memcpy’ </code></pre> <p>The output of the above program is as shown below:</p> <pre><code>Enter 10 lements: 0 1 2 3 4 5 6 7 8 9 Contents of array b: 0 1 2 3 4 5 6 7 8 9 Contents of array a: 0 1 134479874 11136160 11136160 11132916 134514160 134513696 134514171 11132916 </code></pre> <p>Can someone please tell me what's wrong in the above program. </p> <p><strong>Note:</strong> I need to copy data from the buffer to passed array only using memcpy and not via a for loop because of performance reasons in my actual program.</p> <p>Thanks in advance.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload