2015-04-26 3 views
4

Я пытаюсь назначить назначение функции для массива, но при компиляции он не работает.Как назначить вывод функции массиву? В C?

Функция takeInputs должна возвращать массив. И, как и у меня, я думал, что holdInputs - это массив. Однако он, похоже, не компилируется. Какая здесь ошибка?

// Holds the expression that the user enters 
struct Inputs 
{ 
    char word[10]; 
}; 

// Declare these: 
struct Inputs* takeInputs(struct Inputs *userInputs, int numInputs); // must return a pointer to a pointer because returning array 
struct Inputs* printInputs(struct Inputs *userInputs); 

struct Inputs* takeInputs(struct Inputs *userInputs,int numInputs){ 
    /*Inputs: 
     userInputs: an array of struct Inputs, each of which contain a string called "word" 
     numInputs: integer from user 
    */ 

    int i; 
    for (i=0;i<numInputs;i++){ 
     printf("please input the word");   
     fgets(userInputs[i].word,10,stdin); 
    } 


} 

int main(int argc, char const *argv[]){ 

    //user Input should look like this: ./takes_Input.exe 7 
    if (argc!=2){ 
     error("user Input should look like this: ./takes_Input.exe 7"); 
    } 

    // represents the number of words the user is entering 
    int numInputs = atoi(argv[2]); 

    struct Inputs allInputs[numInputs]; 
    struct Inputs holdInputs[numInputs]; 

    holdInputs = takeInputs(allInputs,numInputs); 
    // printInputs(holdInputs); 
    return 0; 
} 

Выход ошибки:

takes_Input.c: In function ‘main’: 
takes_Input.c:53:13: error: assignment to expression with array type 
    holdInputs = takeInputs(allInputs,numInputs); 

Но я думал, что я инициализируется holdInputs как массив ?? Благодарю.

+0

Вы не можете вернуть массив из функции, период (§6.7.6.3, ¶1 _ Объявление функции не должно указывать тип возврата, который является типом функции или массивом type_). Ближайшим вам может быть указатель, и вам нужно будет организовать соответствующее копирование. Вы также не можете назначать массивы друг другу; это основная причина, почему существуют такие функции, как 'strcpy()' и 'memmove()'. –

+1

'takeInputs' возвращает указатель. – immibis

+1

@immibis: за исключением того, что он фактически ничего не возвращает. –

ответ

2

The function takeInputs should return an array. And, as I have it, I thought that holdInputs is an array. However, it doesn't seem to compile. What is the error here?

Ошибка в этом объяснении, что функция не может возвращать массив, Джонатан Леффлера отметил в комментариях.


takes_Input.c:53:13: error: assignment to expression with array type holdInputs = takeInputs(allInputs,numInputs);

But I thought I initialized holdInputs as an array??

Вы действительно объявить holdInputs как массив, и это массив. Хотя вы не инициализировали его, это не должно быть проблемой. В сообщении об ошибке вам сообщается, что вы не можете назначить массив. Например,

char foo[4]; 
foo = "bar";  // This is an error 
strcpy(foo, "bar"); // This is fine and dandy, like sour candy... 

Или взять пример из вашего кода, вы присваиваете в массив здесь:

holdInputs = takeInputs(allInputs,numInputs); 

Возможно, вы имели в виду:

memcpy(holdInputs,takeInputs(allInputs,numInputs),numInputs*sizeof *allInputs); 
+0

Итак, я вижу, что вы пытаетесь сделать. Спасибо. Однако это решение приводит к нечеткой ошибке: 'C: Неизвестная ошибка 2282780' – Sother

+0

Кроме того, memcpy просто копирует память из одного места в другое. 'takeInputs' по-прежнему будет возвращать только один указатель, а не весь массив? поэтому мне непонятно, как это решает проблему? – Sother

+0

Если проблема заключается в «возвращении массива», вам необходимо внимательно прочитать это: ** Вы не можете вернуть массив **. Указатель - это лучшее, что вы можете сделать. Что касается вашего сообщения об ошибке, это похоже на подходящую тему для вашего следующего вопроса. Не видя своего [mcve] (http://stackoverflow.com/help/mcve), сложно с уверенностью сказать, в чем проблема, хотя из * неизвестной его редакции я предлагаю переустановить ваш компилятор и стандартные библиотека может быть лучшим вариантом, возможно, проверка ошибок бит в вашей ОЗУ, если вы обычно сталкиваетесь с нестабильностью при использовании вашего компьютера. – Sebivor

1

Try это,

// Holds the expression that the user enters 
#include <stdlib.h> 
#include <stdio.h> 
#include <string.h> 

struct Inputs { char word[10]; }; 

// Declare these: 
__typeof__(struct Inputs (*)[]) takeInputs(struct Inputs (*userInputs)[], 
int numInputs); // must return a pointer to a pointer because returning array 
void printInputs(struct Inputs (*userInputs)[]); 

void printInputs(struct Inputs (*userInputs)[]){ 
     struct Inputs * ptr = *userInputs; 
     for(;*ptr->word != 0; ptr++){ 
         printf("%s", ptr->word); 
     } 
} 

__typeof__(struct Inputs (*)[]) takeInputs(struct Inputs (*userInputs)[], int numInputs){ 
/*Inputs: 
    userInputs: an array of struct Inputs, each of which contain a string called "word" 
    numInputs: integer from user 
*/ 

int i; 
for (i=0;i<numInputs;i++){ 
       struct Inputs * ptr = (*userInputs+i); 
       printf("please input the word\t");   
       fgets(ptr->word, 10, stdin); 
     } 
    return userInputs; 
} 

int main(int argc, char const *argv[]){ 

//user Input should look like this: ./takes_Input.exe 7 
//if (argc!=2){ 
// printf("user Input should look like this: ./takes_Input.exe 7"); 
// exit(1); 
//} 

// represents the number of words the user is entering 
//const char num[] = {4}; 
int numInputs = 7;//atoi(num);//atoi(argv[2]); 

struct Inputs allInputs[numInputs]; 

/* this array pointer points to allInputs[] */ 
struct Inputs (*holdInputs)[numInputs]; 


holdInputs = takeInputs(&allInputs, numInputs); 

printInputs(holdInputs); 
return 0; 
} 
Смежные вопросы