簡體   English   中英

'['標記之前的語法錯誤

[英]syntax error before '[' token

這是代碼

#include<stdio.h>
#include<sys/types.h>
#include<stdlib.h>
#include<pthread.h>
typedef struct std_thread
{
 char name[20];
 int hallno;
 int empid;
 char dept[5];
}std[5];

void *print(void *args)
{
 struct std_thread *data=(struct std_thread *)args;
 printf("My thread id is %ld\n",pthread_self());
 printf("Thread %d is executing\n",args);
 printf("Name\tHall No\tEmployee ID\tDepartment\n");
 printf("--------------------------------------------------------");
 printf("%s\t%d\t%d\t%s\n",data->name,data->hallno,data->empid,data->dept);
}

int main()
{
 pthread_t th[5];
 int empid=2020;
 int hall=1;
 char dept[2]="IT";
 char *names[]={"dinesh","vignesh","pradeep","prasath","mohan"};
 int t;
 int i;
 int status;
 for(i=0;i<5;i++)
 {
   std[i].name=names[i]; //Getting error from this line
   std[i].hallno=hall;   //Error at this line
   hall++;
   std[i].empid=empid;  //Error at this line
   empid++;
   std[i].dept=dept;     //Error at this line
   status=pthread_create(&th[i],NULL,print,(void *)&std[i]);
   if(status)
   {
    printf("Error creating threads\n");
    exit(0);
   }

 }
 pthread_exit(NULL);
}

編譯此代碼時,出現“ [[']標記之前的語法錯誤”。 這是什么原因呢?

我認為您不是要在頂部typedef

您在此處編寫的內容使std與數組中五個struct類型等效,但隨后您將std當作本身是數組使用。

從第五行刪除單詞typedef ,它應該更接近工作了。

該聲明不執行您認為的操作:

typedef struct std_thread
{
  ...
}std[5];

這將聲明一個名為std_threadstruct ,然后創建一個名為stdtypedef來表示“ 5個struct std_thread對象的數組”。

為了將一個名為std的全局對象聲明為5個struct std_thread的數組,您可能想要這兩個定義之一:

typedef struct std_thread
{
  ...
} std_thread;
std_thread std[5];

// OR

struct std_thread
{
  ..
} std[5];

在第一種情況下,我們還創建了名為std_threadtypedef作為struct std_thread的別名; 在第二種情況下,我們沒有。

此外,正如其他人所述,您不能通過賦值來復制字符數組。 您必須使用諸如strcpy(3)strncpy(3)類的函數來復制它們。 使用strcpy ,必須確保目標緩沖區足夠大以容納所需的字符串。 還請記住, strncpy不一定會將其目標字符串終止null ,因此請謹慎使用。

  1. 您正在嘗試使用賦值復制字符串:

     std[i].name=names[i]; 

     std[i].dept=dept; 

    那行不通。 請改用strcpy或更好的strncpy

  2. 您有錯別字:

     std[i].empid=empdid; //Error at this line 

    您沒有名為empdid的var。

使用字符串復制功能代替分配char數組。

這段代碼:

typedef struct std_thread
{
    char name[20];
    int  hallno;
    int  empid;
    char dept[5];
} std[5];

聲明類型std為5個struct std_thread結構的數組。

這段代碼:

int main()
{
[...]
    int i;
    int status;
    for (i = 0; i < 5; i++)
    {
        std[i].name = names[i]; 

假定std是具有數組或指針類型的變量。

您需要刪除關鍵字typedef以使代碼與變量的使用保持一致。

然后,您可能會遇到字符串分配問題,需要使用字符串復制功能等。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM