I'm really new to programming with C and have encountered the following problem:
When reading about pointers at https://www.tutorialspoint.com/cprogramming/c_pointer_to_an_array.htm, They have the following example:
#include <stdio.h>
int main () {
/* an array with 5 elements */
double balance[5] = {1000.0, 2.0, 3.4, 17.0, 50.0};
double *p;
int i;
p = balance;
/* output each array element's value */
printf( "Array values using pointer\n");
for ( i = 0; i < 5; i++ ) {
printf("*(p + %d) : %f\n", i, *(p + i) );
}
printf( "Array values using balance as address\n");
for ( i = 0; i < 5; i++ ) {
printf("*(balance + %d) : %f\n", i, *(balance + i) );
}
return 0;
}
This example works fine, but when I try to replicate it in my code with a similar situation I'm getting an error.
For example, I create and fill an array with values from a text file. This code works fine and outputs each string in the array as I would expect when finished
#include <stdio.h>
#include <string.h>
#define MAXCHAR 10000
int main() {
FILE *fp;
char* filename = "../MagicProg/Files/MagicProg_csv_ikoria.csv";
char str[MAXCHAR];
char c;
char seps[] = "|";
char *token;
int total_line_count = 0;
fp = fopen(filename, "r");
if (fp == NULL)
{
printf("Could not open file %s", filename);
return 1;
}
for (c = getc(fp); c != EOF; c = getc(fp))
{
if (c == '\n')
{
total_line_count += 1;
}
}
fclose(fp);
fp = fopen(filename, "r");
// declare the arrays
char csv_card_names[total_line_count][30];
int curr_line_index = 0;
int line_token_count = 0;
while (fgets(str, MAXCHAR, fp) != NULL)
{
line_token_count = 0;
token = strtok( str, seps );
while ( token != NULL )
{
if ( curr_line_index > 0 )
{
if ( line_token_count == 0 )
{
strcpy(csv_card_names[curr_line_index - 1], token);
}
}
line_token_count += 1;
token = strtok( NULL, seps );
}
curr_line_index += 1;
}
for ( int i = 0; i < total_line_count; i++ ) {
printf("LINE=\n");
printf("%s\n", csv_card_names[i]);
}
fclose(fp);
return 0;
}
However, In trying to understand arrays I'm trying to re-write the last block of the code where I output the array elements using pointers. From the example above, I try creating a pointer and assigning the array to it just before looping through total line count at the end
...
char *p[30];
p = csv_card_names;
for ( int i = 0; i < total_line_count; i++ ) {
printf("LINE=\n");
printf("%s\n", csv_card_names[i]);
}
But Geany is giving me the error "assignment to expression with array type". I'm not sure how what I'm doing is different than the example, where they assign:
p = balance;
The array (i think) has values of strings equalling 30 chars, so I'm trying to create a point capable of referencing those but am getting this error. any help is appreciated thanks