Я получаю ошибку в той части, где у меня есть struct countOf * rep - PullRequest
0 голосов
/ 13 апреля 2020

Почему я получаю ошибку вроде ожидаемого идентификатора перед '(' before = токен в строке: rep -> current = arr [i]?

typedef struct countOf 
{
    int current;
    int count;
    struct countOf *next_ptr;
} countOf;

typedef countOf *rep;

int main()
{ 
    int arr[9];
    int count = 10;
    rep = (struct countOf*) malloc(count* sizeOf(countOf));
    for (i = 0; i < count; i++ )
      {
        rep -> current = arr[i];
        rep = rep->next_ptr;

      }
}

Ответы [ 3 ]

0 голосов
/ 13 апреля 2020
typedef countOf *rep;

Здесь вы создаете rep как псевдоним для countOf*. Это означает, что rep является типом , а не переменной.

Позже вы сделаете это:

rep = (struct countOf*) malloc(count* sizeOf(countOf));

Но, как я уже сказал, rep - это type , поэтому компилятор жалуется, что вы пытаетесь присвоить ему значение, что не имеет никакого смысла.

Я думаю, что вы вместо этого хотите сделать

countOf* rep = (struct countOf*) malloc(count* sizeOf(countOf));

Вы также должны удалить typedef.

0 голосов
/ 13 апреля 2020

Привет Ваш код имеет много ошибок и l oop дыр, я, конечно, дам вам лучший код, но прежде всего я просто отмечаю ошибки в коде и просто готовлю ваш код к работе. Go просмотрите все комментарии в коде и запустите это на своем компьютере. Это рабочий код, который поможет вам понять ваши ошибки. Я проверил это на turbo C.

#include<stdio.h>
#include<conio.h>
#include<malloc.h>

typedef struct countOf
{
    int current;
    int count;//why??
    struct countOf *next_ptr;//why, u r using continuous blocks
}countOfNode;
// typedef make countOfNode as an dataType
countOfNode *rep;
//Now rep is global pointer of type struct countOf

int main()
{
    int arr[10];//why 9 while we have 10 count everywhere in code
    int count = 10;
    int i;
    rep = (countOfNode*)malloc(count * sizeof(countOfNode));
    printf("Enter 10 values in array if you want to assign value from array structure array");
    for (i = 0; i < count; i++ )
    { clrscr();// to not keep useless on screen;
      printf("Enter %dth value in array",i+1);
      scanf("%d",&arr[i]);
    }
    for (i = 0; i < count; i++ )
      {
      /*any value you want to assign to current
      but what is arr[i]??? it contains no value
    */
      //rep->current = arr[i];
    //Currently there is no next pointer
       // rep = rep->next_ptr;

       //You assign it 10 continuos blocks so what is the use of ptr???
       //For pointer dont assign continuos blocks make it dynamic
       rep[i].current = arr[i];

      }
     printf("Data in structure rep");
     for(i=0 ; i<count; i++)
     {
      printf("%dth node have \t%d\n",i+1,rep[i].current);
     }


}

Теперь вы можете проверить приведенный ниже код с небольшими улучшениями в вашем коде. Это не лучший способ, но он поможет вам лучше понять. Мы можем написать код гораздо лучше

#include<stdio.h>
#include<conio.h>
#include<malloc.h>

typedef struct countOf
{
    int current;
    struct countOf *next_ptr;//it keep address of next node
}countOfNode;

countOfNode *rep;
//Now rep is global pointer of type struct countOf we just keep offset(base address in this)

int main()
{
    int count = 10;
    int i;
    countOfNode *tracker, *tmp;
    rep = (countOfNode*)malloc(sizeof(countOfNode));//initializing first time
    printf("Enter value To store");
    scanf("%d",&rep->current);//storing value for first node
    rep->next_ptr = NULL;//assigin null becaus there is no next node
    tracker = rep; // we move tracker alway, rep will just keep the offset
    for(i=1; i<count; i++)//0 already assigned above
    {
      tmp = (countOfNode*)malloc(sizeof(countOfNode));//initializing current node
      printf("Enter value To store");
      scanf("%d",&tmp->current);//storing value for first node
      tmp->next_ptr = NULL;//assigin null becaus there is no next node
      tracker->next_ptr = tmp; // we move tracker alway, rep will just keep the offset
      tracker = tmp;//tracker jump to next node
    }


    printf("Data in structure rep");
    tracker = rep;
    for(i=0; i<count; i++)//0 already assigned above
    {
       printf("%d\t",tracker->current);
       tracker = tracker->next_ptr;//jump to next
    }
    getch();

}
0 голосов
/ 13 апреля 2020

В этой строке

rep = (struct *countOf) malloc(count* sizeOf(countOf));

есть две ошибки. Во-первых, rep - это имя типа, а не объект. Во-вторых, вместо struct *countOf должно быть не менее struct countOf *. though this casting is redundant

Обратите внимание на это, если вы будете правильно переписывать этот оператор

rep = rep->next_ptr;

с заменой имени типа на имя переменной, тем не менее, этот оператор будет вызывать неопределенное поведение, поскольку элемент данных next_ptr не был инициализирован.

Если вы хотите иметь глобальный указатель, вы можете написать, например,

rep head;

или

rep head = NULL;

то же самое.

...