Passing vector to functions

Asked

Viewed 1,181 times

7

How do I pass a vector to a function? Something that, on the Moon, would be like this:

vector = {"V", "e", "t", "o", "r"}
function getVector(vector, pos)
    return vector[pos]
end
print(getVector(vector, 1))
Output: "V"

I tried so:

#include <stdio.h>
void main() {
    char vector[5] = {"V", "e", "t", "o", "r"};
    char getVector(char vector[], int pos) {
        return vector[pos];
    }
    printf("%c", getVector(vector, 0));
}

The mistakes:

G:\PROJETOS\C\test.c    In function 'main':
3   5   G:\PROJETOS\C\test.c    [Error] excess elements in char array initializer
3   5   G:\PROJETOS\C\test.c    [Error] (near initialization for 'vector')
3   5   G:\PROJETOS\C\test.c    [Error] excess elements in char array initializer
3   5   G:\PROJETOS\C\test.c    [Error] (near initialization for 'vector')
3   5   G:\PROJETOS\C\test.c    [Error] excess elements in char array initializer
3   5   G:\PROJETOS\C\test.c    [Error] (near initialization for 'vector')
3   5   G:\PROJETOS\C\test.c    [Error] excess elements in char array initializer
3   5   G:\PROJETOS\C\test.c    [Error] (near initialization for 'vector')
  • Did something go wrong in your code? The way it is, it should work...

  • Yes, I edited the question, there are the mistakes.

  • 1

    Hehe looked at the function itself with so much focus that I didn’t pay attention to the code around... : P

3 answers

7


The code has some problems:

  • The Main() need to return a int. Some compilers accept different from this but it is out of the standard, learn to do everything by default.
  • One function cannot be inside the other. And the called function must be declared before its use. Its definition may be later but it’s more practical to do before (next to the statement, so you don’t have to put its header twice) in simple cases like this.
  • You declared the vector as type char but put strings inside it as elements. There is a difference between single and double quotes. The character literal is with single quotes.

Code:

#include <stdio.h>

char getVector(char vector[], int pos) {
    return vector[pos];
}

int main() {
    char vector[5] = {'V', 'e', 't', 'o', 'r'};
    printf("%c", getVector(vector, 0));
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Solved. Great answer.

  • @Gabrielsales You can vote for everything you find useful on website, even in things that it was not you who asked. Acceptance that you can only choose an answer to a question of your own. At your discretion, but I don’t know if you know this. mgibsonbr’s response is good too, it’s very similar to mine. Although I’m not as ready as mine I think you should vote for him too.

  • int main() also not recommended in C, as it represents a variable list of parameters, different from C++, where the signature would be correct. int main(void) would be correct in C.

  • 1

    First there is a terminology error there: http://answall.com/a/32450/101. This has no practical relevance. This way there is no parameter declared, so nothing will be used. Several arguments can come. But since there are no parameters, it does not matter. It would matter if it were another function because then a call with arguments would go through the compilation. But the main() is not called by code but by the operating system.

  • An error of terminology? I am referring to parameters, not arguments, arguments occur in the call, not in the statement, and this you are referring to?

  • The relevance is the title of following the pattern, as you yourself seek to recommend. http://stackoverflow.com/a/8692152/1000282

  • There is no list of parameters there, for you to put a list of parameters you have to use varargs (...). Without parameter you cannot access anything, so there is no problem. There would be a problem in the call that could pass arguments and compile, which would not happen in this case. So much so that the mandatory only in C99 (a standard does not adopt by all compilers mainstream). Even C++ didn’t want to do this because it didn’t make any sense. And even C99 compilers don’t usually generate Warning when you don’t have the void in this case of so absurd that it is the recommendation.

  • Patterns serve two things: to ensure that compiles on all compilers. Everyone I know compiles like this even when C99 is on; to avoid errors by carelessness. In this case nothing will cause problem. Then follow the pattern to follow, s/ none advantage is silly, so compilers don’t care about it either. It’s not because it’s in the pattern that’s right. You have to say explicitly that you want this in the compiler.

  • C++ doesn’t do this because it has nothing to do with K&R prototypes. C has a history apart at this point that makes int main() in C to be something totally different from int main() in C++, for historical reasons. K&R is not encouraged in current code, except for crazy compatibility, or very old code base, e.g., the source code of the Vim editor.

  • 1

    Finally, the use of int main() reinforces the use of int foo() in C, when the right would be int foo(void). The use of foo(42) could pass without noticing and functioning, while with the practice of int foo(void) this would never happen because it would generate compilation error. For me, it is already reason enough to adopt the practice.

Show 5 more comments

6

In C you cannot pass vectors by value, only by reference (i.e. you need to pass a pro vector pointer, not the vector itself). However, the C syntax allows you to define your function in this way:

char getVector(char vector[], int pos) {

And the compiler ensures that the vector automatically decays to a pointer. Source.

However, the same is not true for multidimensional vectors:

char vector[5][2] = {"V", "e", "t", "o", "r"};

char getVector(char vector[][], int pos, int pos2) { // Não funciona

char getVector(char vector[][2], int pos, int pos2) { // Funciona

char getVector(char **vector, int pos, int pos2) { // Funciona

Source. Source.

As for your compilation errors:

  • In C there is a difference between a string and a single character: strings are bounded by double quotes, and characters by single quotes. So your vector initialization should be:

    char vector[5] = {'V', 'e', 't', 'o', 'r'};
    
  • You cannot create functions within other functions in C. Pass your getVector out of function main.

  • I voted but did not understand the first paragraph. The vector is an implicit reference. At this specific point it works the same as Java. You declare that the parameter is vector but the argument you pass normal because it is already an opaque pointer as in Java (although the internal details are different).

  • 1

    @bigown I confess that I do not understand very well about vectors in C (I learned alone before college, after never used again). I knew that one could pass structs by value, and I assumed that the same applied to arrays, but in the linked answer I saw that this is not the case. I tried to answer based on what I read there, but I may not have expressed myself very well...

5

The other answers already solve your problem, but I would like to collaborate.

In Lua there is no difference between "V", 'V' and [[V]], how do you read here. All treated as strings. But in C single quotes and double quotes has different meanings.

In C and C++, single quotes are used for a single character and double quotes for strings. In the case of strings, the compiler includes a character null or '\0', to identify the end of the string.

So that:

char str1[] = "Hello";

It amounts to this, with the '\0' in the end:

char str2[] = { 'H','e','l','l','o','\0' };

Example: ideone

Browser other questions tagged

You are not signed in. Login or sign up in order to post.