数组的C指针问题
我对使用C编程非常陌生,遇到了以下问题: 在上阅读指针时,他们有以下示例:数组的C指针问题,c,pointers,C,Pointers,我对使用C编程非常陌生,遇到了以下问题: 在上阅读指针时,他们有以下示例: #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
#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;
}
我认为这个数组的字符串值等于30个字符,所以我试图创建一个能够引用这些字符串的点,但是我得到了这个错误。感谢您的帮助,char*p[30]不是指针,而是指针数组。与任何其他数组一样,它不能被分配
您需要将其声明为指向30个字符数组的指针
char*p[30]=…char*p[30]-是指针数组char[30],例如指向char的30个指针,而char*p[30]-是指向char[30]数组的指针,例如指向包含30个字符的字符数组的指针。关于为什么需要paren,请参阅一些提供指针基本讨论的链接。提示:用x[y]代替*x+y。这不仅减少了输入,而且对熟悉C的人来说更有意义。记住,你可以做x[y][z]甚至更深层的嵌套结构,这不会飞,因为计算这些偏移量真的不容易。值得注意的是,char*通常比char*p[30]好因为在处理指针时,长度在很大程度上是不相关的,需要以更具体的方式指定,比如作为附加函数参数。
#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;
}
...
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]);
}
p = balance;