尝试输入使用的数组索引的最后一个指针

Trying to input in last pointer of array index used

我正在尝试输入名称并将它们保存在指针中。然后从我之前输入的最后一个索引开始添加更多客户。但我做不对。有小费吗? 很抱歉把所有的代码都放在上面只是为了更好地理解。

#include<stdio.h>
    #define SIZE 50
    
    int main(){
    int x;
    char name[SIZE][SIZE];
    char *namePtr[SIZE][SIZE];
    
    printf("enter no of customers ");
    scanf("%d", &x);
    
    puts("enter customer names");
    
    for(size_t i = 0, j = 0; i < x; ++i, ++j){
        scanf("%s", &name[i][j]);
        namePtr[i][j] = &name[i][j];
        }
        
        puts("\nPrinting using pointer\n");
        
        for(size_t i = 0, j = 0; i < x; ++i, ++j){
            printf("%s ", &*namePtr[i][j]);
        }
        puts("\n");
        
        int c;
        printf("2nd number of customers to add ");
        scanf("%d", &c);
        
        puts("enter customer names");
        
        for(size_t i = x , j = 0; i < c+x; ++i, ++j){
            scanf("%s", &*namePtr[i][j]);
        }
        puts("printing customers combined\n");
        
        for(size_t i = 0, j = 0; i < x+c; ++i, ++j){
            printf("%s ", &*namePtr[i][j]);
        }
        return 0;
    }

结果是 阿里迈克威尔 (NULL) (NULL)

记住第一个客户数量是 3 第二个是 2

这个声明

char *namePtr[SIZE][SIZE];

没有意义。

您需要声明指向字符串的 SIZE 指针,例如

char *namePtr[SIZE];

由于声明无效,以下 for 循环也没有意义。

而且这个for循环

for(size_t i = x , j = 0; i < c+x; ++i, ++j){
    scanf("%s", &*namePtr[i][j]);
}

调用未定义的行为,因为数组 namePtr 中索引从 x 开始的指针未初始化。

看来你需要的是下面这样的东西。

#include <stdio.h>

#define SIZE 50

int main( void ) 
{
    char name[SIZE][SIZE];
    char * namePtr[SIZE];
    
    printf("enter no of customers ");

    int n = 0;
    scanf( "%d", &n );
    
    printf( "enter %d customer names\n", n );
    
    for ( int i = 0; i < n; i++ )
    {
        scanf( "%49s", name[i] );
        namePtr[i] = name[i];
    }
    
    puts( "\nPrinting using pointer" );
    
    for ( int i = 0; i < n; i++ )
    {
        printf( "%s ", namePtr[i] );
    }
    putchar( '\n' );
    
    printf( "\n2nd number of customers to add " );

    int m = 0;
    scanf( "%d", &m );
    
    printf( "enter %d customer names\n", m );

    for ( int i = n; i < m + n; i++ )
    {
        namePtr[i] = name[i];
        scanf( "%49s", namePtr[i] );
    }
    
    puts( "\nprinting customers combined" );
        
    for ( int i = 0; i < n + m; ++i )
    {
        printf( "%s ", namePtr[i] );
    }
    putchar( '\n' );
    
    return 0;
}

尝试运行程序。