簡體   English   中英

用 c 中的指針編寫 function

[英]writing function with pointers in c

我寫了這段代碼:

#include <stdio.h>
void transpose(int *Al[]){
int x=0;
int z=0;
int k=1;
while (*Al[z] != "\0") {
    int c=*Al[z];
    if (c>x)
        x=c;
   z++;
}
printf("%d ",x);
for(int o=0;o<6;o++){
   for(int i=0 ;i<x;i++ ) {
       int *p = Al[i];
       int l=*p;
       if(k<l)
       printf("%d ",*(p+k));
       else
           printf("   ");
   }
   k++;
   printf("\n");
   }

   }
   int main() {
   int A[] = {5, -5, 14, 5, 2};
   int B[] = {3, 6, 11};
   int C[] = {4, 1, -3, 4};
   int D[] = {6, 2, 7, 1, 8, 2};
   int E[] = {2, 15};
   int F[] = {3, 4, -2};
   int *All[] = {A, B, C, D, E, F, NULL};
   transpose(All);
   }

function 獲得一個指向不同數組的數組,我需要使用指針打印 arrays 應該是:

-5 6   1 2 15 4
14 11 -3 7    -2
5      4 1     
2        8      
         2

但是這段代碼不打印任何東西。 此外,它指向第一個值的 arrays 是數組的大小。 我試過這個:

void transpose(int *Al[]){
int x=0;
int z=0;
int k=1;
for(int o=0;o<5;o++){
    for(int i=0 ;i<6;i++ ) {
        int *p = Al[i];
        int l=*p;
        if(k<l)
            printf("%d ",*(p+k));
        else
            printf("   ");
    }
    k++;
    printf("\n");
    }

 }

它只工作我需要替換循環中的五和六 五是他 arrays -1 中最大的尺寸,所以我會知道要打印多少行,六到多少 arrays 總這樣我就可以知道我有多少列應該打印。 有解決方案嗎?

while循環中的條件

while (*Al[z] != "\0") {

沒有意義。 表達式*Al[z]具有int類型,而字符串文字"\0"具有char *類型。

也不清楚為什么在這個循環中會出現幻數6

for(int o=0;o<6;o++){

無需顯式計算列數,因為您的哨兵值等於NULL

我可以建議例如以下解決方案

#include <stdio.h>

void transpose( int * Al[] )
{
    int rows = 0;
    
    for ( int **p = Al; *p != NULL; ++p )
    {
        if ( rows < **p ) rows = **p;
    }
    
    if ( rows ) --rows;
    
    for ( int i = 0; i < rows; i++ )
    {
        for ( int **p = Al; *p != NULL; ++p )
        {
            if ( i + 1 < **p ) printf( "%2d ", *( *p + i + 1 ) );
            else printf( "   " );
        }
        
        putchar( '\n' );
    }
    
}

int main(void) 
{
    int A[] = {5, -5, 14, 5, 2};
    int B[] = {3, 6, 11};
    int C[] = {4, 1, -3, 4};
    int D[] = {6, 2, 7, 1, 8, 2};
    int E[] = {2, 15};
    int F[] = {3, 4, -2};
    int *All[] = { A, B, C, D, E, F, NULL };
   
    transpose( All );
   
    return 0;
}

程序 output 是

-5  6  1  2 15  4 
14 11 -3  7    -2 
 5     4  1       
 2        8       
          2 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM