C将指针传递给数组到函数问题

时间:2013-05-14 18:59:52

标签: c pointers

用Google搜索并且无法找到这里出现的问题,指针正确传递,但它无法正常工作。

程序应该找到字符数组/字符串的长度。

这里有什么问题?只要总是给零长度!

#include <stdio.h>
#include <stdbool.h>

int stringlength(char *); // Declare function in the beggining (because C)

main()
{
    char testString[100]; // Character array where we'll store input from command line (unsafely)
    char *arrayPointer; // Pointer that will point to array so it can be passed to function
    int length; // Integer for length of string
    printf("Please enter in a string: \n");
    scanf("s", &testString[0]); // Get input
    arrayPointer = &testString[0]; // Point the pointer to the array
    printf("Pointer to array %p\n-----------------\n", arrayPointer); // Output pointer
    stringlength(arrayPointer); // And use the function
    printf("Length is %d\n", length); // Output the length of the string...
}

stringlength(char *stringArray)
{
    int i = 0; // Counter variable
    int length = 0; // Length variable
    bool done = false; // Boolean for loop
    while(!done)
    {
        printf("Character is %c\n", stringArray[i]); // Output character
        printf("Memory location %p\n", &stringArray[i]); // Output memory location of character

        if(stringArray[i] == '\x00') // If the current array slot is a null byte we've reached the end of the array
        {
            done = true; // Null byte found, we're all done here
            return length;
        } else {
            length++; // Not a null byte so increment length!
        }
        i++; // Counter for moving forward in array
    }
}

输出是:

mandatory@MANDATORY:~/Programming/C$ ./a.out
Please enter in a string: 
testing
Pointer to array 0x7fffc83b75b0
-----------------
Character is    
Memory location 0x7fffc83b75b0
Character is 
Memory location 0x7fffc83b75b1
Length is 0

2 个答案:

答案 0 :(得分:3)

你有一些问题:

  1. main应声明返回int

    int main(void)
    
  2. 您的scanf格式错误。使用:

    scanf("%s", &testString[0]);
    
  3. stringlength()实施中的签名与原型不符。确保它是:

    int stringlength(char *stringArray)
    
  4. stringlength()不会返回长度。添加:

    return length;
    

    在该功能的最后。

  5. 您未分配到length中的main()。将呼叫更改为stringlength()以实际使用返回值:

    length = stringlength(arrayPointer);
    
  6. main()应该返回一些内容。可能是0。添加:

    return 0;
    

    main()

  7. 的末尾

答案 1 :(得分:2)

我想你想要

    scanf("s", &testString[0]); // Get input

    scanf("%s", &testString[0]); // Get input