2017-02-18 6 views
0

Ich weiß, wir sind in der Lage, ähnliche ausdrucken „sssss“ wirdWie ein 2D-Array an eine Funktion übergeben modifizieren

void c(char *s)                    
{                        
    int i = 0;                     

    while (s[i])                     
    s[i++] = 's';                    
}     



int  main()                     

    {                        
     char str[] = "hello";                   

     c(str);                      
     printf("%s\n", str);                   
     return (0);                     
    } 

in diesem Fall eine Zeichenfolge durch eine Funktion zu ändern.

Aber wie kann ich ein 2D-Array auf die gleiche Weise wie ich für eine Zeichenfolge ändern? Ich meine, ohne das Array zurückzugeben.

void c(char **s)                   
{                        
    int i = 0;                    
    int j = 0;                    

    while (s[i])                    
    {                       
     j = 0;                     
     while (s[i][j])                   
     {                      
      s[i][j++] = 's';                 
     }                      
     i++;                     
    }                       

}                        

int  main()                    
{                        
    char tab[2][2];                    
    tab[0][0] = 'a';                   
    tab[0][1] = 'b';                   
    tab[1][0] = 'c';                   
    tab[1][1] = 'd';                   
    c(tab);                      
    printf("%c%c\n%c%c", tab[0][0], tab[0][1], tab[1][0], tab[1][1]);       
    return (0);                     
} 

Hier ist eine Idee, wie wir es tun könnten.

Ich hoffe, ich war klar genug?

Antwort

0

Die Definition sollte die Länge enthalten. Im Anschluss wird ein gutes Buch sein: http://www.firmcodes.com/pass-2d-array-parameter-c-2/

nichtig c (char (* s) [Länge])

#include <stdio.h> 
void c(int len, char (*s)[len]) 
{ 
    int i = 0; 
    int j = 0; 

    while (i < len) 
    { 
     j = 0; 
     while (s[i][j]) 
     { 
      s[i][j++] = 's'; 
     } 
     i++; 
    } 

} 

int  main() 
{ 
    char tab[2][2]; 
    tab[0][0] = 'a'; 
    tab[0][1] = 'b'; 
    tab[1][0] = 'c'; 
    tab[1][1] = 'd'; 
    c(2, tab); 
    printf("%c%c\n%c%c", tab[0][0], tab[0][1], tab[1][0], tab[1][1]); 
    return (0); 
} 
0

Sicher, es ist das Gleiche. Mit jeder Dimensionszählung.

void c(char **s, int stringCount) 
{ 
    int i = 0, j = 0; 

    for (j = 0; j < stringCount; ++j) 
    { 
     i = 0; 
     while (s[j][i]) 
     { 
      s[j][i++] = 's'; 
     } 
    } 
} 

int  main() 
{ 
    char *tab[2] = { "str1", "str2" }; 
    c(tab, 2); 
    printf("%c%c\n%c%c", tab[0][0], tab[0][1], tab[1][0], tab[1][1]); 
    printf("%s\n%s", tab[0], tab[1]); 
    getchar(); 
    return (0); 
} 
+0

Wie rufe ich die Funktion? Ich habe versucht, funk (s), aber es funktioniert nicht :( – Beben

+0

Vielen Dank für Ihre Antwort! :) – Beben

Verwandte Themen