0

I just want to understand pointer to pointer. I write a simple app to calculate the bill of the electric:

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

#define MAXLENGTH 40
#define MAXSTUFF 40

int main()
{
    int n;
    float watt[MAXSTUFF];
    float hours[MAXSTUFF];
    
    printf("How many is your stuff : ");
    scanf("%d", &n);
    getchar();
    
    char stuff[n][MAXLENGTH];
    char * ptrStuff[n];
    char **ptrStuff2 = NULL;
    
    for(int i = 0; i < n; i++) {
        printf("Input your stuff %d: ", i+1);
        fgets(stuff[i], sizeof(stuff[i]), stdin);
                
        printf("Number of watt %d: ", i+1);
        scanf("%f", &watt[i]);
        
        printf("Number of hours %d: ", i+1);
        scanf("%f", &hours[i]);
        
        getchar();
    }
    
    //hitung
    float jum = 0;
    
    for(int i = 0; i < n; i++) {
        //the formula
        jum += watt[i] * 1.4672 * hours[i] * hours[i];
        
    }
    
    //initialize
    
    ptrStuff2 = ptrStuff;
    
    for(int i = 0; i < n; i++)
    {
        //puts(stuff[i]);
        printf("%s \n", ptrStuff2[i]);
    }
    
    printf("Total Rp : %f\n", jum);
    
    return 0;
}

But why the result for printing the stuff got weird? I compiled with gcc and -Wall -Wextra option but no warning found. What I missed? Thanks. I am a newbie.

  • 2
    You probably want to replace `for(int i = 0; i < strlen(stuff[i]); i++)` with `for(int i = 0; i < n; i++)`, otherwise it does not make sense. – Eugene Sh. Jul 06 '21 at 13:56
  • @EugeneSh. What you said was make sense. But what I mean by that statement of strlen(stuff[i]) is I want to really take the number of char of stuff. Because we know that "car" and "computer" have different number of char. – Agung Sudrajat Jul 06 '21 at 14:04
  • Then it is not what you are doing. `puts` is printing a whole string. – Eugene Sh. Jul 06 '21 at 14:07
  • I change the scanf("%d", &n); with scanf("%d\n",&n); the result is fine but still look ugly: – Agung Sudrajat Jul 06 '21 at 14:20
  • `puts` adds a newline when printing, and `fgets` reads the newlines from your input and puts it in your strings. The result is that when printing you get *two* newlines. Either use `fputs` for printing, or strip newlines from your strings. – HAL9000 Jul 06 '21 at 14:45
  • I found a solution for (1): by putting getchar(); just after the scanf statement. But number (2) is still a mistery. – Agung Sudrajat Jul 06 '21 at 14:46

0 Answers0