Stiliyan Koev Stiliyan Koev - 10 months ago 76
C Question

Passing a char array as parameter in method, C langauge

this is my first (and I hope last) C language coding. It is for my coursework and I have some troubles.


  1. I want to pass a char[] as a parameter to a method

  2. I want to copy this char[] to another char[]. For this I am using strcpy.



So when I do:

main(){
char asd[20] = {"asd"};
insert(asd);
}

void insert(char value[]) //here value[] contains only 'd'
{
...code...
}


So basically, it is passing just one char, not the array. I tried with:

main(){
char *asd[20] = {"asd"};
insert(asd);
}

void insert(char *value[]) //here value[] contains 'asd'
{
char *secondArray[20] = {' '}
strcpy(secondArray,value); // char** incompatible with "const char*"
}


And I am stucked.

Answer Source

You have not declared your strings correctly, they should be char arrays not array for char pointers

char *asd[20] = {"asd"};

to

char asd[20] = {"asd"};

and

 char *secondArray[20] = {'   '}

to

 char secondArray[20] = {'   '}

Program after corrections:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void insert(char *value);

int main(){
  char asd[20] = {"asd"};
  insert(asd);
  return 0;
}

void insert(char *value) //here value[] contains 'asd'
{
   char secondArray[20] = {"   "};
   strcpy(secondArray,value); // char** incompatible with "const char*"
   printf("%s",secondArray);
   return;
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download