--- In [email protected], Rick <[EMAIL PROTECTED]> wrote:
>
> I have a program I'm trying to write and can't figure out
> how to do it the way I want.
<snip>
> Can someone show me the proper way to reference the char arrays
> within a function? Do I actually need to de-reference them?
> 
> Here is what I've written which is, obviously, wrong.
> 
> #include <stdio.h>
> #include <stdlib.h>
> 
> extern   void loadcArray(char [][], int);
> extern   void printcArray(char [][], int);
> 
> #define  MAXSTRLN 16
> 
> int main(int argc, char *argv[])
> {
>      int result;
>      char array2[5][MAXSTRLN] = {"string1", "String2",
>          "String3", "string4", "string5"};
>      int a2size = (sizeof(array2) / MAXSTRLN);

It's better to change this to
  int a2size = sizeof( array2) / sizeof( array2 [0]);
This way you can easily get the allocated size of any array, no matter
what its elements consist of (be it structs, unions, or pointers).

>      loadcArray(array2, a2size);
>      printcArray(array2, a2size);
> 
>      system("PAUSE");
> 
>      return 0;
> }
> 
> 
> void loadcArray(char cArray[][], int alen)
> {
>           int ix;
>           char val[MAXSTRLN];
> 
>           for (ix = 0; ix < alen; ix++)
>           {
>               printf("Enter a string value for array[%d]: ", ix);
>               fscanf(stdin, "%s", val);
>               strncpy(cArray[ix][0], val, MAXSTRLN-1);
>           }

Why do you use "strncpy()" here? You have NOT terminated the copied
string explicitly. While this might not impose trouble if you're
dealing with global or static variables, it's still a good chance to
introduce unnecessary errors. I would use "strcpy()" here.

>           printf("Finished loading %d values\n", ix);
> 
>           return;
> }
> 
> 
> void printcArray(char cArray[][], int alen)
> {
>       int ix;
> 
>       printf("\n");
>       for (ix = 0; ix < alen; ix++)
>       {
>           printf("Array[%d] = %s\n", ix, cArray[ix][0]);
>       }

Leave out the "[0]" after "cArray"; "cArray [ix]" denotes a char[]
whereas your code denotes one single char although the printf() format
string requires a char* here. This is your main error.

>       return;
> }

Please let us know whether there are any errors which I have overlooked.

Regards,
Nico

Reply via email to