carraysmikroc

How do I receive a char array in a C function?


I wish to split a "string" by the character ','. The string holds a GPS NMEA encoded string, but that is of no matter.

My problem is that sometimes the parameter from the function that processes this char array is empty... Like nothing is in the array.

How should I correctly pass a "char string[]" to a function so that I may operate on a that parameter as I sent it(as a char array, not a char pointer to an array).

I also need to specify that I'm using mikroC for PIC.

Here is my code as of right now:

char* GPS_sateliti;
char CsatInView[] = 
"$GPGSV,3,2,11,14,25,170,00,16,57,208,39,18,67,296,40,19,40,246,00*74";

GPS_sateliti = GrupeazaDupaVirgule(CsatInView, 2);

char* GrupeazaDupaVirgule( char deGasit[],int nrVirgule ){
    int cVirgule = 1;
    char* pch = strtok (deGasit,",");

    while (pch != 0)
    {
       pch = strtok (0, ",");
       cVirgule++;
       if(nrVirgule == cVirgule){
          break;
    }
}
return pch;
}

The function that operates on the char array received as a parameter in debug mode, before entering the function the char array is fine, after entering it, it seems to be empty The function that operates on the char array received as a parameter in debug mode, before entering the function the char array is fine, after entering it, it seems to be empty

It may be that I should receive a pointer to an array of chars?? Any sort of advice is welcome. Thank you


Solution

  • With a pointer :

    char* arr; 
    yourFunction(arr);
    

    If you wish to initialize it before :

    char* arr = malloc(51 * sizeof(char)); // Allocate a memory place of 50 because strings are null terminated in C
    yourFunction(arr);
    

    An other way to allocate memory to an array :

    char* arr = calloc(50, sizeof(char)); // Allocate 50 memory place which size if the size of a char
    

    With a string :

    char arr[50];
    char* ptr = arr;
    yourFunction(ptr);
    

    You have to know that it is impossible in C to know the size of an array when using pointer. The only thing you can do is to parse the size of the string as a parameter :

    size_t size = 50;
    char arr[size];
    char* ptr = arr;
    yourFunction(ptr, size);
    

    If you wish to understand in detail how pointer works and how to iterate them, may be this post can help you. I think it is very interesting. Globally, you iterate through an array via a pointer like this :

    for ( int i = 0; i < size; i++)
        printf("Current pointed value in the array : %c\n", ptr[i]); // or arr[i]
    

    I guess you understand why giving the size of a pointed array as a parameter is important. Sometimes you can avoid using this parameter like this :

    for ( int i = 0; i != '\0'; i++) // Because strings are null-terminated in C.
        // Do something