Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Your problems start with your specification. If I understand you correctly, you want to have a function where you pass an array of characters and a length. The size of your array of input characters will be between 1 and <code>len</code>? However, your function has no way of knowing what the size of your array <code>num</code> is. If you wanted this to work, you would need to define your function as </p> <pre><code>const char * extendBinary(char *num, size_t num_len, int len); </code></pre> <p>so that your function doesn't overrun your buffer pointed to by <code>num</code>. Note that I replaced <code>char num[]</code> with <code>char *num</code> as this is the common mechanism for passing a pointer. You cant pass pointers to arrays and then dereference that pointer and get back the original type (that includes its size) -- that's just one thing that C doesn't let you do, so just use a normal pointer and a separate size variable.</p> <p>Finally, you'll have to deal with memory allocation unless you want a memory leak. Thus, you could simply say that whom ever calls extendBinary should free it's return value when done with it.</p> <pre><code>const char * extendBinary(char *num, size_t num_len, int len) { char *ret = malloc(len + 1); int i; memset(ret, '0', len); ret[len] = 0; strncpy(&amp;ret[len - num_len], num, num_len); return ret; } int main(void) { char arr[] = {'1', '0', '1'}; const char *formatted = extendBinary(arr, sizeof(arr), 8); printf("%s\n", formatted); free(formatted); return 0; } </code></pre>
    singulars
    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.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      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