c - 递增指向字符串数组的指针返回 NULL

标签 c arrays string pointers

我正在尝试将一个字符串数组传递给一个函数以打印到屏幕上。第一个字符串打印正常。但是,前面的字符串为空,因此不打印任何内容。如果我将指针直接指向第一个字符串而不是数组,我可以将它递增字符数组的大小,并且一切都可以正确打印。如果我尝试增加指向字符串数组的指针,那是我得到空值的地方。为什么会发生这种情况以及如何正确打印数组。如果考虑到它使用的 C 标准,我也会使用 visual studio。

我认为错误不在于调用,因为传递的指针指向字符串数组地址。

//How I'm passing the array
char headings[4][20] = { "Name", "Record Number", "Quantity", "Cost"};
int widths[4] = {20, 20, 20, 20 };
headers(&headings[0][0], &widths[0], 4);


//Function
void headers(char **heads, int *columnWidths, int noOfColumns) {
    int headLength = 0;
    printf("|");
    for (int i = 0; i < noOfColumns; i++) {
        headLength += printf("%*s|", *columnWidths, heads);
        columnWidths++;
        heads ++;
    }
    printf("\n");
    for (int i = 0; i < headLength+1; i++) {
        printf("-");
    }
    printf("\n");
}

这是我得到的输出:

|                Name|                    |                    |                       |

但我期待这样的输出:

|                Name|       Record Number|            Quantity|                   Cost|

最佳答案

如果您有一个二维数组 heading,您的 headers 函数也应该接受一个二维数组。虽然数组在传递给函数时通常会退化为指针,但类型 char** headschar headings[4][20] 不同。你的编译器也应该警告你。

下面的代码打印出正确的输出。

#include <stdio.h>
#include <string.h>

//Function
void headers(char heads[4][20], int *columnWidths, int noOfColumns) {
    int headLength = 0;
    printf("|");
    for (int i = 0; i < noOfColumns; i++) {
        headLength += printf("%*s|", *columnWidths, *heads);
        columnWidths++;
        heads ++;
    }
    printf("\n");
    for (int i = 0; i < headLength+1; i++) {
        printf("-");
    }
    printf("\n");
}

int main(){
    char headings[4][20] = { "Name", "Record Number", "Quantity", "Cost"};
    int widths[4] = {20, 20, 20, 20};
    headers(headings, &widths[0], 4);
}

注意:您还可以更改 headers 函数以接受 char heads[][20],但不接受 char[][]因为那会给你一个明显的编译器错误。

关于c - 递增指向字符串数组的指针返回 NULL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54632274/

相关文章:

命令行参数 : use of space between program argument, 和参数的参数

c - Raspberry Pi 上 armv6 中 log10 数学函数的错误结果

c - 换行符未出现在 proc 文件中

ios - 如何声明新数组来附加元组数组?

java - 如何将标点符号从字符串末尾移动到开头?

c - 测试并发数据结构

php - 有条件地组合 PHP 数组

c# - C#中的 bool 变量和字符串值比较

string - 为什么 strings.HasPrefix 比 bytes.HasPrefix 快?

xcode - 将 Swift 中 HTTP 请求返回的 NSData 转换为字符串